JSP动态网页开发原理详解

一、什么是jsp?

     jsp全称是java server pages,它和servle技术一样,都是sun公司定义的一种用于开发动态web资源的技术。
  jsp这门技术的最大的特点在于,写jsp就像在写html,但它相比html而言,html只能为用户提供静态数据,而jsp技术允许在页面中嵌套java代码,为用户提供动态数据。

二、jsp原理

2.1、web服务器是如何调用并执行一个jsp页面的?

  浏览器向服务器发请求,不管访问的是什么资源,其实都是在访问servlet,所以当访问一个jsp页面时,其实也是在访问一个servlet,服务器在执行jsp的时候,首先把jsp翻译成一个servlet,所以我们访问jsp时,其实不是在访问jsp,而是在访问jsp翻译过后的那个servlet,例如下面的代码:

index.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
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%>" rel="external nofollow" >

  <title>first jsp</title>

 </head>

 <body>
  <%
    out.print("hello jsp");
  %>
 </body>
</html>

  当我们通过浏览器访问index.jsp时,服务器首先将index.jsp翻译成一个index_jsp.class,在tomcat服务器的work\catalina\localhost\项目名\org\apache\jsp目录下可以看到index_jsp.class的源代码文件index_jsp.java,index_jsp.java的代码如下:

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=utf-8");
   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>first jsp</title>\r\n");
   out.write("\t\r\n");
   out.write(" </head>\r\n");
   out.write(" \r\n");
   out.write(" <body>\r\n");
   out.write("  ");

    out.print("hello jsp");

   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);
   }
  } finally {
   _jspxfactory.releasepagecontext(_jspx_page_context);
  }
 }
}

  我们可以看到,index_jsp这个类是继承 org.apache.jasper.runtime.httpjspbase这个类的,通过查看tomcat服务器的源代码,可以知道在apache-tomcat-6.0.20-src\java\org\apache\jasper\runtime目录下存httpjspbase这个类的源代码文件,如下图所示: 

我们可以看看httpjsbase这个类的源代码,如下所示:

/*
 * licensed to the apache software foundation (asf) under one or more
 * contributor license agreements. see the notice file distributed with
 * this work for additional information regarding copyright ownership.
 * the asf licenses this file to you under the apache license, version 2.0
 * (the "license"); you may not use this file except in compliance with
 * the license. you may obtain a copy of the license at
 *
 *   http://www.apache.org/licenses/license-2.0
 *
 * unless required by applicable law or agreed to in writing, software
 * distributed under the license is distributed on an "as is" basis,
 * without warranties or conditions of any kind, either express or implied.
 * see the license for the specific language governing permissions and
 * limitations under the license.
 */

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;
}

  httpjspbase类是继承httpservlet的,所以httpjspbase类是一个servlet,而index_jsp又是继承httpjspbase类的,所以index_jsp类也是一个servlet,所以当浏览器访问服务器上的index.jsp页面时,其实就是在访问index_jsp这个servlet,index_jsp这个servlet使用_jspservice这个方法处理请求。

2.2、jsp页面中的html排版标签是如何被发送到客户端的?

浏览器接收到的这些数据

<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
  <base href="http://localhost:8080/javaweb_jsp_study_20140603/" rel="external nofollow" >

  <title>first jsp</title>

 </head>

 <body>
  hello jsp
 </body>
</html>

都是在_jspservice方法中使用如下的代码输出给浏览器的:

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>first jsp</title>\r\n");
   out.write("\t\r\n");
   out.write(" </head>\r\n");
   out.write(" \r\n");
   out.write(" <body>\r\n");
   out.write("  ");

    out.print("hello jsp");

   out.write("\r\n");
   out.write(" </body>\r\n");
   out.write("</html>\r\n");

  在jsp中编写的java代码和html代码都会被翻译到_jspservice方法中去,在jsp中编写的java代码会原封不动地翻译成java代码,如<%out.print("hello jsp");%>直接翻译成out.print("hello jsp");,而html代码则会翻译成使用out.write("<html标签>\r\n");的形式输出到浏览器。在jsp页面中编写的html排版标签都是以out.write("<html标签>\r\n");的形式输出到浏览器,浏览器拿到html代码后才能够解析执行html代码。

2.3、jsp页面中的java代码服务器是如何执行的?

  在jsp中编写的java代码会被翻译到_jspservice方法中去,当执行_jspservice方法处理请求时,就会执行在jsp编写的java代码了,所以jsp页面中的java代码服务器是通过调用_jspservice方法处理请求时执行的。

2.4、web服务器在调用jsp时,会给jsp提供一些什么java对象?

  查看_jspservice方法可以看到,web服务器在调用jsp时,会给jsp提供如下的8个java对象

pagecontext pagecontext;
httpsession session;
servletcontext application;
servletconfig config;
jspwriter out;
object page = this;
httpservletrequest request,
httpservletresponse response

  其中page对象,request和response已经完成了实例化,而其它5个没有实例化的对象通过下面的方式实例化

pagecontext = _jspxfactory.getpagecontext(this, request, response,null, true, 8192, true);
 application = pagecontext.getservletcontext();
 config = pagecontext.getservletconfig();
 session = pagecontext.getsession();
 out = pagecontext.getout();

 这8个java对象在jsp页面中是可以直接使用的,如下所示:

<%
    session.setattribute("name", "session对象");//使用session对象,设置session对象的属性
    out.print(session.getattribute("name")+"<br/>");//获取session对象的属性
    pagecontext.setattribute("name", "pagecontext对象");//使用pagecontext对象,设置pagecontext对象的属性
    out.print(pagecontext.getattribute("name")+"<br/>");//获取pagecontext对象的属性
    application.setattribute("name", "application对象");//使用application对象,设置application对象的属性
    out.print(application.getattribute("name")+"<br/>");//获取application对象的属性
    out.print("hello jsp"+"<br/>");//使用out对象
    out.print("服务器调用index.jsp页面时翻译成的类的名字是:"+page.getclass()+"<br/>");//使用page对象
    out.print("处理请求的servlet的名字是:"+config.getservletname()+"<br/>");//使用config对象
    out.print(response.getcontenttype()+"<br/>");//使用response对象
    out.print(request.getcontextpath()+"<br/>");//使用request对象
%>

运行结果如下:

 

2.5、jsp最佳实践

  jsp最佳实践就是jsp技术在开发中该怎么去用。

  不管是jsp还是servlet,虽然都可以用于开发动态web资源。但由于这2门技术各自的特点,在长期的软件实践中,人们逐渐把servlet作为web应用中的控制器组件来使用,而把jsp技术作为数据显示模板来使用。其原因为,程序的数据通常要美化后再输出:让jsp既用java代码产生动态数据,又做美化会导致页面难以维护。让servlet既产生数据,又在里面嵌套html代码美化数据,同样也会导致程序可读性差,难以维护。因此最好的办法就是根据这两门技术的特点,让它们各自负责各的,servlet只负责响应请求产生数据,并把数据通过转发技术带给jsp,数据的显示jsp来做。

2.6、tomcat服务器的执行流程

  

第一次执行:

  • 客户端通过电脑连接服务器,因为是请求是动态的,所以所有的请求交给web容器来处理
  • 在容器中找到需要执行的*.jsp文件
  • 之后*.jsp文件通过转换变为*.java文件
  • *.java文件经过编译后,形成*.class文件
  • 最终服务器要执行形成的*.class文件
  • 第二次执行:

    因为已经存在了*.class文件,所以不在需要转换和编译的过程

    修改后执行:

           1.源文件已经被修改过了,所以需要重新转换,重新编译。

    到此这篇关于jsp动态网页开发原理详解的文章就介绍到这了,更多相关jsp动态网页开发原理内容请搜索硕编程以前的文章或继续浏览下面的相关文章希望大家以后多多支持硕编程!

    相关文章