JavaWeb總結十四、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

複製代碼
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>First Jsp</title>
13     
14   </head>
15   
16   <body>
17     <%
18         out.print("Hello Jsp");
19     %>
20   </body>
21 </html>
複製代碼

  當我們通過瀏覽器訪問index.jsp時,服務器首先將index.jsp翻譯成一個index_jsp.class,在Tomcat服務器的work\Catalina\localhost\項目名\org\apache\jsp目錄下可以看到index_jsp.class的源代碼文件index_jsp.java,index_jsp.java的代碼如下:

複製代碼
 1 package org.apache.jsp;
 2 
 3 import javax.servlet.*;
 4 import javax.servlet.http.*;
 5 import javax.servlet.jsp.*;
 6 import java.util.*;
 7 
 8 public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
 9     implements org.apache.jasper.runtime.JspSourceDependent {
10 
11   private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
12 
13   private static java.util.List _jspx_dependants;
14 
15   private javax.el.ExpressionFactory _el_expressionfactory;
16   private org.apache.AnnotationProcessor _jsp_annotationprocessor;
17 
18   public Object getDependants() {
19     return _jspx_dependants;
20   }
21 
22   public void _jspInit() {
23     _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
24     _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
25   }
26 
27   public void _jspDestroy() {
28   }
29 
30   public void _jspService(HttpServletRequest request, HttpServletResponse response)
31         throws java.io.IOException, ServletException {
32 
33     PageContext pageContext = null;
34     HttpSession session = null;
35     ServletContext application = null;
36     ServletConfig config = null;
37     JspWriter out = null;
38     Object page = this;
39     JspWriter _jspx_out = null;
40     PageContext _jspx_page_context = null;
41 
42 
43     try {
44       response.setContentType("text/html;charset=UTF-8");
45       pageContext = _jspxFactory.getPageContext(this, request, response,
46                   null, true, 8192, true);
47       _jspx_page_context = pageContext;
48       application = pageContext.getServletContext();
49       config = pageContext.getServletConfig();
50       session = pageContext.getSession();
51       out = pageContext.getOut();
52       _jspx_out = out;
53 
54       out.write('\r');
55       out.write('\n');
56 
57 String path = request.getContextPath();
58 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
59 
60       out.write("\r\n");
61       out.write("\r\n");
62       out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
63       out.write("<html>\r\n");
64       out.write("  <head>\r\n");
65       out.write("    <base href=\"");
66       out.print(basePath);
67       out.write("\">\r\n");
68       out.write("    \r\n");
69       out.write("    <title>First Jsp</title>\r\n");
70       out.write("\t\r\n");
71       out.write("  </head>\r\n");
72       out.write("  \r\n");
73       out.write("  <body>\r\n");
74       out.write("    ");
75 
76         out.print("Hello Jsp");
77     
78       out.write("\r\n");
79       out.write("  </body>\r\n");
80       out.write("</html>\r\n");
81     } catch (Throwable t) {
82       if (!(t instanceof SkipPageException)){
83         out = _jspx_out;
84         if (out != null && out.getBufferSize() != 0)
85           try { out.clearBuffer(); } catch (java.io.IOException e) {}
86         if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
87       }
88     } finally {
89       _jspxFactory.releasePageContext(_jspx_page_context);
90     }
91   }
92 }
複製代碼

  我們可以看到,index_jsp這個類是繼承 org.apache.jasper.runtime.HttpJspBase這個類的,通過查看Tomcat服務器的源代碼,可以知道在apache-tomcat-6.0.20-src\java\org\apache\jasper\runtime目錄下存HttpJspBase這個類的源代碼文件,如下圖所示:

  

我們可以看看HttpJsBase這個類的源代碼,如下所示:

複製代碼
 1 /*
 2  * Licensed to the Apache Software Foundation (ASF) under one or more
 3  * contributor license agreements.  See the NOTICE file distributed with
 4  * this work for additional information regarding copyright ownership.
 5  * The ASF licenses this file to You under the Apache License, Version 2.0
 6  * (the "License"); you may not use this file except in compliance with
 7  * the License.  You may obtain a copy of the License at
 8  * 
 9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package org.apache.jasper.runtime;
19 
20 import java.io.IOException;
21 
22 import javax.servlet.ServletConfig;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27 import javax.servlet.jsp.HttpJspPage;
28 import javax.servlet.jsp.JspFactory;
29 
30 import org.apache.jasper.compiler.Localizer;
31 
32 /**
33  * This is the super class of all JSP-generated servlets.
34  *
35  * @author Anil K. Vijendran
36  */
37 public abstract class HttpJspBase 
38     extends HttpServlet 
39     implements HttpJspPage 
40         
41     
42 {
43     
44     protected HttpJspBase() {
45     }
46 
47     public final void init(ServletConfig config) 
48     throws ServletException 
49     {
50         super.init(config);
51     jspInit();
52         _jspInit();
53     }
54     
55     public String getServletInfo() {
56     return Localizer.getMessage("jsp.engine.info");
57     }
58 
59     public final void destroy() {
60     jspDestroy();
61     _jspDestroy();
62     }
63 
64     /**
65      * Entry point into service.
66      */
67     public final void service(HttpServletRequest request, HttpServletResponse response) 
68     throws ServletException, IOException 
69     {
70         _jspService(request, response);
71     }
72     
73     public void jspInit() {
74     }
75 
76     public void _jspInit() {
77     }
78 
79     public void jspDestroy() {
80     }
81 
82     protected void _jspDestroy() {
83     }
84 
85     public abstract void _jspService(HttpServletRequest request, 
86                      HttpServletResponse response) 
87     throws ServletException, IOException;
88 }
複製代碼

  HttpJspBase類是繼承HttpServlet的,所以HttpJspBase類是一個Servlet,而index_jsp又是繼承HttpJspBase類的,所以index_jsp類也是一個Servlet,所以當瀏覽器訪問服務器上的index.jsp頁面時,其實就是在訪問index_jsp這個Servlet,index_jsp這個Servlet使用_jspService這個方法處理請求。

2.2、Jsp頁面中的html排版標籤是如何被髮送到客戶端的?

瀏覽器接收到的這些數據

複製代碼
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 2 <html>
 3   <head>
 4     <base href="http://localhost:8080/JavaWeb_Jsp_Study_20140603/">
 5     
 6     <title>First Jsp</title>
 7     
 8   </head>
 9   
10   <body>
11     Hello Jsp
12   </body>
13 </html>
複製代碼

都是在_jspService方法中使用如下的代碼輸出給瀏覽器的:

複製代碼
 1 out.write('\r');
 2       out.write('\n');
 3 
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 
 7       out.write("\r\n");
 8       out.write("\r\n");
 9       out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
10       out.write("<html>\r\n");
11       out.write("  <head>\r\n");
12       out.write("    <base href=\"");
13       out.print(basePath);
14       out.write("\">\r\n");
15       out.write("    \r\n");
16       out.write("    <title>First Jsp</title>\r\n");
17       out.write("\t\r\n");
18       out.write("  </head>\r\n");
19       out.write("  \r\n");
20       out.write("  <body>\r\n");
21       out.write("    ");
22 
23         out.print("Hello Jsp");
24     
25       out.write("\r\n");
26       out.write("  </body>\r\n");
27       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對象

複製代碼
1 PageContext pageContext;
2 HttpSession session;
3 ServletContext application;
4 ServletConfig config;
5 JspWriter out;
6 Object page = this;
7 HttpServletRequest request, 
8 HttpServletResponse response
複製代碼

  其中page對象,request和response已經完成了實例化,而其它5個沒有實例化的對象通過下面的方式實例化

1 pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);
2 application = pageContext.getServletContext();
3 config = pageContext.getServletConfig();
4 session = pageContext.getSession();
5 out = pageContext.getOut();

這8個java對象在Jsp頁面中是可以直接使用的,如下所示:

複製代碼
 1 <%
 2         session.setAttribute("name", "session對象");//使用session對象,設置session對象的屬性
 3         out.print(session.getAttribute("name")+"<br/>");//獲取session對象的屬性
 4         pageContext.setAttribute("name", "pageContext對象");//使用pageContext對象,設置pageContext對象的屬性
 5         out.print(pageContext.getAttribute("name")+"<br/>");//獲取pageContext對象的屬性
 6         application.setAttribute("name", "application對象");//使用application對象,設置application對象的屬性
 7         out.print(application.getAttribute("name")+"<br/>");//獲取application對象的屬性
 8         out.print("Hello Jsp"+"<br/>");//使用out對象
 9         out.print("服務器調用index.jsp頁面時翻譯成的類的名字是:"+page.getClass()+"<br/>");//使用page對象
10         out.print("處理請求的Servlet的名字是:"+config.getServletName()+"<br/>");//使用config對象
11         out.print(response.getContentType()+"<br/>");//使用response對象
12         out.print(request.getContextPath()+"<br/>");//使用request對象
13 %>
複製代碼

運行結果如下:

  

2.5、Jsp最佳實踐

  Jsp最佳實踐就是jsp技術在開發中該怎麼去用。

  不管是JSP還是Servlet,雖然都可以用於開發動態web資源。但由於這2門技術各自的特點,在長期的軟件實踐中,人們逐漸把servlet作爲web應用中的控制器組件來使用,而把JSP技術作爲數據顯示模板來使用。其原因爲,程序的數據通常要美化後再輸出:讓jsp既用java代碼產生動態數據,又做美化會導致頁面難以維護。讓servlet既產生數據,又在裏面嵌套html代碼美化數據,同樣也會導致程序可讀性差,難以維護。因此最好的辦法就是根據這兩門技術的特點,讓它們各自負責各的,servlet只負責響應請求產生數據,並把數據通過轉發技術帶給jsp,數據的顯示jsp來做。

2.6、Tomcat服務器的執行流程

  

第一次執行:

  1. 客戶端通過電腦連接服務器,因爲是請求是動態的,所以所有的請求交給WEB容器來處理
  2. 在容器中找到需要執行的*.jsp文件
  3. 之後*.jsp文件通過轉換變爲*.java文件
  4. *.java文件經過編譯後,形成*.class文件
  5. 最終服務器要執行形成的*.class文件

第二次執行:

  1. 因爲已經存在了*.class文件,所以不在需要轉換和編譯的過程

修改後執行:

1.源文件已經被修改過了,所以需要重新轉換,重新編譯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章