JSP原理初探

什么是JSP

JSP的英文名称是Java Server Page,它是sun公司定义的一种用于开发动态网页的技术。
下面让我们来带着几个问题来学习JSP:

  1. Web服务器是如何实现调用并执行一个JSP页面的?
  2. JSP页面中的Html排版标签是如何被发送到客户端的?
  3. 服务器是如何执行JSP中的Java代码的?
  4. Web服务器在调用JSP时会给JSP什么Java对象?

问题一解答:
当客户端向Web服务器发送JSP请求的时候,JSP引擎就会解析JSP,然后将JSP转成Servlet,再编译成.class文件交由服务器来执行,最后Web服务器把JSP页面发给客户端(浏览器),浏览器就可以显示请求的JSP页面了。在第一次执行请求SP页面的时候会比较慢,因为Web服务器还没有JSP相应的Servlet以及.class文件。所以,下一次请求相同的JSP页面的时候就会比较快,直接执行Web服务器中缓存有的.class文件。
那么,JSP相应的java和.class文件保存在哪里呢?以Tomcat为例,保存在\apache-tomcat-6.0.44\apache-tomcat-6.0.44\work\Catalina\工程名\org\apche目录下。
那么,JSP里面的内容是怎么样被解析的呢?下面先看一个JSP页面和解析后的Java文件:

JSP 源文件

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
  </head>

  <body>
    This is my JSP page. <br>

    <% Date date=new Date(); %>
    <%=date %>

  </body>
</html>

解析后的JSP页面

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=GB18030");
      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('\r');
      out.write('\n');

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write(" <head>\r\n");
      out.write(" <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write(" \r\n");
      out.write(" <title>My JSP 'index.jsp' starting page</title>\r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\"> \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write(" </head>\r\n");
      out.write(" \r\n");
      out.write(" <body>\r\n");
      out.write(" This is my JSP page. <br>\r\n");
      out.write(" \r\n");
      out.write(" ");

       Date date=new  Date();

      out.write("\r\n");
      out.write(" ");
      out.print(date );
      out.write("\r\n");
      out.write(" \r\n");
      out.write(" </body>\r\n");
      out.write("</html>\r\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
可以知道,解析后的JSP的Java类继承自:org.apache.jasper.runtime.HttpJspBase,并且实现了org.apache.jasper.runtime.JspSourceDependent接口,翻看Tomcat源码看看这个类和接口的实现:
HttpJspBase类
package org.apache.jasper.runtime;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import javax.servlet.jsp.JspFactory;

import org.apache.jasper.compiler.Localizer;

/** * This is the super class of all JSP-generated servlets. * * @author Anil K. Vijendran */
public abstract class HttpJspBase extends HttpServlet implements HttpJspPage {

    protected HttpJspBase() {
    }

    public final void init(ServletConfig config) 
    throws ServletException 
    {
        super.init(config);
    jspInit();
        _jspInit();
    }

    public String getServletInfo() {
    return Localizer.getMessage("jsp.engine.info");
    }

    public final void destroy() {
    jspDestroy();
    _jspDestroy();
    }

    /** * Entry point into service. */
    public final void service(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException 
    {
        _jspService(request, response);
    }

    public void jspInit() {
    }

    public void _jspInit() {
    }

    public void jspDestroy() {
    }

    protected void _jspDestroy() {
    }

    public abstract void _jspService(HttpServletRequest request, 
                     HttpServletResponse response) 
    throws ServletException, IOException;
}



package org.apache.jasper.runtime;

/** * Interface for tracking the source files dependencies, for the purpose * of compiling out of date pages. This is used for * 1) files that are included by page directives * 2) files that are included by include-prelude and include-coda in jsp:config * 3) files that are tag files and referenced * 4) TLDs referenced */
JspSourceDependent 接口//返回当前页面包含的所有的资源文件名列表
package org.apache.jasper.runtime;

/** * Interface for tracking the source files dependencies, for the purpose * of compiling out of date pages. This is used for * 1) files that are included by page directives * 2) files that are included by include-prelude and include-coda in jsp:config * 3) files that are tag files and referenced * 4) TLDs referenced */

public interface JspSourceDependent {

   /** * Returns a list of files names that the current page has a source * dependency on. */
    // FIXME: Type used is Object due to very weird behavior 
    // with Eclipse JDT 3.1 in Java 5 mode
    public Object getDependants();

}

看完这个类和接口,返回来分析一下JSP页面如何被解析的。

  • JSP的脚本片段直接翻译成普通Java代码
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
解析成--> String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

   <%
       Date date=new  Date();
     %>
     -->解析成Date date=new  Date();
  • JSP脚本表达是直接使用out输出
   <%=date %>--> out.print(date );
  • Html排本标签使用out输出
out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <base href=\"");
      out.print(basePath);
      out.write("\">\r\n");
      out.write("    \r\n");
      out.write("    <title>My JSP 'index.jsp' starting page</title>\r\n");
      out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");
      out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");
      out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
      out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");
      out.write("\t<!--\r\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");
      out.write("\t-->\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("    This is my JSP page. <br>\r\n");
      out.write("    \r\n");
      out.write("    ");

       Date date=new  Date();

      out.write("\r\n");
      out.write("    ");
      out.print(date );
      out.write("\r\n");
      out.write("    \r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");
  • Web服务器传入八大java对象
    1 PageContext pageContext :代表页面上下文,该对象用于范文JSP之间的共享数据;
    2 PageContext _jspx_page_context:代表当前页面上下文
    3 HttpSession session
    4 ServletContext application:Web应用程序上下文,所有用户公用一个对象;
    5 ServletConfig config :代表Servlet初始化信息
    6JspWriter out
    7 JspWriter _jspx_out
    8 Object page
 public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=GB18030");
      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;
      ……………………
      ……………………
      ……………………
      } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }

到这里,我们就对JSP有了初步的了解。

你可能感兴趣的:(jsp)