专业编程基础技术教程

网站首页 > 基础教程 正文

图解JSP运行原理和过程

ccvgpt 2025-04-26 17:01:22 基础教程 27 ℃

JSP运行过程

  1. WEB容器JSP页面的访问请求时,它将把该访问请求交给JSP引擎去处理。Tomcat中的JSP引擎就是一个Servlet程序,它负责解释和执行JSP页面。
  2. 每个JSP页面在第一次被访问时,JSP引擎先将它翻译成一个Servlet源程序,接着再把这个Servlet源程序编译成Servlet的class类文件,然后再由WEB容器像调用普通Servlet程序一样的方式来装载和解释执行这个由JSP页面翻译成的Servlet程序。

图解JSP运行原理和过程

实例解释

我们用一个实例来说明上面的JSP运行过程:

1. Hello.jsp文件内容如下:




    

Hello!

当前时间:${currentTime}

2. servlet代码

下面代码通过注解来处理/hello的请求, 并在代码中将请求转发到上述hello.jsp.

@WebServlet
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DateFormat dateFormat = new SimpleDateFormat;
        String currentTime = dateFormat.format(new Date);
        req.setAttribute(,currentTime);
        req.getRequestDispatcher.forward(req,resp);
    }
}

3. 运行服务器并访问

这时用everything搜索本机上的hello_jsp.java文件, 可以找到如下内容的文件:


package org.apache.jsp.WEB_002dINF.jsp

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
 org.apache.jasper.runtime.JspSourceImports {

  ...

  // 这里是最主要的方法, 我们在jsp文件里的内容, 都在这里通过out.write写入到输出中.
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {    
    try {
      response.setContentType
      pageContext = _jspxFactory.getPageContext(this, request, response,
 null, true, 8192, true)
      _jspx_page_context = pageContext
      application = pageContext.getServletContext
      config = pageContext.getServletConfig
      session = pageContext.getSession
      out = pageContext.getOut
      _jspx_out = out

      out.write
      out.write
      out.write
      out.write
      out.write
      out.write
      out.write
      out.write
      out.write
      out.write(当前时间:")
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(, java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null))
      out.write(\n")
      out.write
      out.write
      out.write
    } catch (java.lang.Throwable t) {
      ...
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context)
    }
  }
}

这里可以看出, 当我们访问需要jsp文件时, tomcat的Jasper组件会将jsp文件翻译成java文件, 然后再编译. 继续用everything搜索hello_jsp, 可以发现还有一个文件叫hello_jsp.class, 侧面印证了我们的论断.

图形解释

我们先用图形大概解释一下上述流程:

简洁易懂. 接下来我们在思考每一步的具体实现, 看下图:

1.客户端请求jsp文件, web服务器(tomcat等)根据jsp文件生成java文件.

2.java文件生成对应的class字节码文件,字节码文件是可以通过classloader加载进虚拟机的.

3.web容器加载class字节码文件.

4.web容器通过反射等手段建立hello_jsp实例.

5.调用对应的jspInit来进行实例初始化.

6.调用_jspservice, 响应用户请求.

7.调用jspDestroy销毁jsp_hello实例.

Tags:

最近发表
标签列表