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有了初步的了解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSP 中,session 是用于在服务器端存储用户信息的一种机制,它可以在多个请求之间共享数据。session 是通过 HttpSession 接口实现的,它的工作原理如下: 1. 当用户第一次访问某个 JSP 页面时,服务器会为该用户创建一个 session 对象,并将该 session 对象的 ID 存储在一个名为 JSESSIONID 的 cookie 中,然后将该 cookie 发送给客户端。 2. 当用户发送其他请求时,客户端会自动将 JSESSIONID 的 cookie 发送给服务器,服务器会通过该 ID 来查找对应的 session 对象。 3. 当用户关闭浏览器或者 session 超时时,session 对象会被销毁,其中存储的用户信息也会被清除。 在 JSP 中,我们可以通过内置对象 session 来访问 session 对象,例如 session.getAttribute() 可以获取 session 中存储的属性值,session.setAttribute() 可以向 session 中存储属性值。session 对象是一个 Map 集合,可以存储任何类型的数据,例如基本数据类型、对象、集合等。需要注意的是,session 对象的属性值必须是可序列化的,否则会抛出 NotSerializableException 异常。 使用 session 可以方便地实现用户状态的管理,例如登录状态、购物车信息等。但是需要注意,如果 session 中存储的数据过多或者过于频繁地访问 session,会占用较多的服务器资源,降低服务器的性能。因此,在使用 session 时需要注意合理使用,避免滥用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值