JSP 基础(一)

JavaServletPage(JSP)

一 JSP简介

      Servlet的缺陷
      –Servlet的编码、部署和调试任务繁琐
      –生成动态网页繁琐,不利于项目分工
    为了弥补Servlet的这些缺陷,SUN公司在Servlet的基础上推出了JSP技术作为解决方案
 
    采用JSP技术编写动态页面  
     –由HTML语句和嵌套在其中的Java代码组成的一个普通文本文件
     –JSP页面的扩展名必须为.jsp
 

二 JSP运行机制与生命周期

JSP的执行包括7个阶段

 2.1 JSP页面翻译阶段:Web容器第一次接收到某个JSP页面的请求后,首先把自动将该页面翻译成Servlet代码。

  

 1 <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
 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>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24     <%
25          out.print("Hello Jsp");
26     %>
27   </body>
28 </html>

执行了上面的这个.jsp后,会在D:apache-tomcat-6.0.20workCatalinalocalhost项目名orgapachejsp下发现一个index_jsp.class文件和一个index_jsp.java文件

打开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=ISO-8859-1");
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('
');
55       out.write('
');
56 
57 String path = request.getContextPath();
58 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
59 
60       out.write("
");
61       out.write("
");
62       out.write("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
");
63       out.write("<html>
");
64       out.write("  <head>
");
65       out.write("    <base href="");
66       out.print(basePath);
67       out.write("">
");
68       out.write("    
");
69       out.write("    <title>My JSP 'index.jsp' starting page</title>
");
70       out.write("	<meta http-equiv="pragma" content="no-cache">
");
71       out.write("	<meta http-equiv="cache-control" content="no-cache">
");
72       out.write("	<meta http-equiv="expires" content="0">    
");
73       out.write("	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
");
74       out.write("	<meta http-equiv="description" content="This is my page">
");
75       out.write("	<!--
");
76       out.write("	<link rel="stylesheet" type="text/css" href="styles.css">
");
77       out.write("	-->
");
78       out.write("  </head>
");
79       out.write("  
");
80       out.write("  <body>
");
81       out.write("    ");
82 
83          out.print("Hello Jsp");
84     
85       out.write("
");
86       out.write("  </body>
");
87       out.write("</html>
");
88     } catch (Throwable t) {
89       if (!(t instanceof SkipPageException)){
90         out = _jspx_out;
91         if (out != null && out.getBufferSize() != 0)
92           try { out.clearBuffer(); } catch (java.io.IOException e) {}
93         if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
94       }
95     } finally {
96       _jspxFactory.releasePageContext(_jspx_page_context);
97     }
98   }
99 }

 2.2 JSP页面编译阶段:index_jsp.java文件编译成index_jsp.class文件。

 2.3 JSP页面类装载阶段:Web容器装载新生成的Servlet类。

 2.4 JSP页面实例化阶段:Web容器创建实例。

 2.5 JSP页面初始化阶段:web容器调用Servlet示例的_jspInit()方法。

 2.6 JSP页面服务阶段:容器创建一个新线程来处理客户的请求,Servlet对象的_jspService()方法运行。

 2.7 JSP页面的销毁:servlet对象的_jspDestory()方法。 

如果一个Web应用程序中包含有JSP页面,部署这个应用时,在JSP生命周期中,整个翻译和编译步骤只发生一次。JSP一旦被翻译和编译,就像其他Servlet一样了。其实只有在第一次执行的时候有性能上的差别。

JSP通常用于简化创建产生文本的Servlet,二Servlet更适合用于发送原生字节到客户端或所需要用java源代码完全控制源代码的场合。

三 JSP语法与语义

   JSP网页主要有元素(Element)和模板数据(Template Data)两部分组成。

  元素可以分成三个不同的类别:脚本元素,指令,动作。(下面进行解释) 

四 脚本元素

 在JSP中有三种不同类型的脚本元素:scriptlet,脚本表达式,声明。

  4.1 Scriptlet     

JSP脚本片断(scriptlet)用于在JSP页面中编写多行Java代码。语法格式:
    <%  多行java代码  %>

  在<% %>中可以定义变量、编写语句,不能定义方法。

eg:

 1  <%
 2       /*声明变量*/ 
 3       int sum=0;
 4  
 5      /*编写语句*/
 6      for (int i=1;i<=100;i++){
 7          sum+=i;
 8     }
 9       out.println("<h1>Sum="+sum+"</h1>");
10     
11       out.print("Hello Jsp");
12     %>

  4.2 脚本表达式

 JSP脚本表达式(expression)用于将程序数据输出到客户端。语法:

               <%= 变量或表达式 %>

eg:

 1 <body>
 2 
 3     <%
 4         int[] balls = new int[6];
 5         Random r = new Random();
 6         for (int i = 0; i < 6;) {
 7             boolean flag = true;
 8             int temp = r.nextInt(33) + 1;
 9             for (int j = 0; j <= i; j++) {
10                 if (balls[j] == temp) {
11                     flag = false;
12                     break;
13                 }
14             }
15             if (flag) {
16                 balls[i] = temp;
17                 i++;
18     %>
19     <div class="red"><%=temp%></div>
20 
21     <%
22              }
23         }
24     %>
25     <div class="blue"><%=r.nextInt(16) + 1%></div>
26 </body>

 JSP引擎在翻译脚本表达式时,会将程序数据转成字符串,然后在相应位置用out.print(…) 将数据输给客户端。
JSP脚本表达式中的变量或表达式后面不能有分号(;)

4.3 声明

   JSP页面中编写的所有代码,默认会翻译到servlet的service方法中, 而Jsp声明中的java代码被翻译到_jspService方法的外面。语法:
    <%! java代码  %>
  所以,JSP声明可用于定义JSP页面转换成的Servlet程序的静态代码块、成员变量和方法 。 
  多个静态代码块、变量和函数可以定义在一个JSP声明中,也可以分别单独定义在多个JSP声明中。
  JSP隐式对象的作用范围仅限于Servlet的_jspService方法,所以在JSP声明中不能使用这些隐式对象。

可以在JSP程序中声明一个或多个变量。但是每一个声明语句都必须以分号结束

eg:

1 <%! String s="hello"; %>
2 <%! int a,b,c; %>
3 <%! java.util.Date date=new java.util.Date(); %>
1 <%!
2         public void method(){
3                 
4         }
5      %>

五 注释 

六 JSP指令

七 JSP标准动作

八 JSP隐式对象

原文地址:https://www.cnblogs.com/hellokitty1/p/4939230.html