JSP組成元素

HTML樣板文字

同HTML語法

Script Elements

註解(comment):

<%-- This is a JSP comment --%>
 
<%-- 
   This is a JSP comment can span
   in multiple lines
--%>


運算式(expression):

// The syntax of an expression is as follows:
<?= expression ?>

// For example, if you want to display the current date and time,
// you can use an expression as follows:
<%= new java.util.Date()%>


程序片段(scriptlet):

// The following illustrates the syntax of scriptlet:
<% // any java source code here %>

// In this example, we display a greeting message based on the current time of the day
// using the scriptlet.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <title>JSP syntax</title>
    </head>
    <body>
        <%
                // using scriptlet
                java.util.Calendar now = new java.util.GregorianCalendar();
                String tod = "";
 
                if (now.get(now.HOUR_OF_DAY) < 12) {
                    tod = "Morning!";
                } else if (now.get(now.HOUR_OF_DAY) < 18) {
                    tod = "Afternoon!";
                } else {
                    tod = "Evening!";
                }
        %>
 
        Good <%=tod%>
 
    </body>
</html>


宣告(declaration):

//For example, if you want to declare a variable x,
// you can use JSP declaration as follows:
<%! int x = 10; %>

// The final semicolon(;) is required.

The difference between a variable using declaration and a variable is declared using scriptlet is that a variable declared using declaration tag is accessible by all methods, while a variable declared using scriptlet is only accessible to the _jspservice() method of the generated servlet from the JSP page.


指令(directive):

<%@ page contentType="text/html"%>
  • page:定義頁面的屬性
    • language:預設為Java
    • importimport="java.sql.Date, java.util.*, java.io.*"(不要加分號semicolon)
    • session:預設為true。只有當此屬性為true時,隱含變數session才會出現
    • errorPage:指定處理發生錯誤的網頁
    • isErrorPage:是否為處理錯誤的網頁。參考上面的說明,預設為false
    • contentType:此網頁輸出資料的MIME形態與回應文字資料的編碼
    • pageEncoding:此網頁所用的編碼。省略時依據contentType屬性
    • isElIgnored:是否忽略EL,即視EL為字串,不做運算。預設為false
    • buffer:指定輸出緩衝區的大小。預設為8kb
  • taglib:標籤庫指令描述了要使用的JSP標籤庫(JSTL
  • include:告知JSP編譯器把另外一個文件內容完全包含至當前JSP文件中
    • 靜態包含(效能高):<%@ include file="/public/header.html" %>
    • 動態包含(可以傳參數):<jsp:include page="/public/herder.html" />
    • 動態包含(可以傳參數):<c:import url="/public/herder.html"">

Expression Language

(empty)

Standard Actions

(empty)

JSP Standard Tag Library

作用:

EL表达式可以简化JSP页面,减少大量Java代码。但是,对于一些场景,你会发现依然必须在JSP中嵌入Java代码才可以使得页面呈现出想要的结果,比如:

  • 依据某个条件决定显示的HTML内容——导航栏根据用户是否登录的状态显示不同的内容
  • 循环显示一段HTML内容,比如博客列表中每一个条目的文章

因为HTML本身并没有<if><for>这样的标签来完成动态生成网页的任务。 所幸的是,Java EE提供了这样的扩展标签库——JSTL,它不仅能提供条件判断、循环等常用实现程序逻辑的标签,还提供很多扩充标签让开发者能够更加方便的实现业务功能。

JSTL与EL表达式相互配合使用,就能将基本在JSP中消除Java代码了。

set

<c:set var="salary" scope="session" value="${2000*2}"/>
<c:out value="${salary}"/>

out

<c:out value="{blog.url}" escapeXml="true" default="/blog" />

forEach

<c:forEach var="i" begin="1" end="5">
   Item <c:out value="${i}"/><p>
</c:forEach>

<c:forEach var="blog" items="${blogs}">
  <c:out value="${blog.title}"/><p>
</c:forEach>

if

<c:set var="salary" value="${2000*2}"/>
<c:if test="${salary > 2000}">
   <p>My salary is: <c:out value="${salary}"/><p>
</c:if>

choose

<c:set var="salary" scope="session" value="${2000*2}"/>
<p>Your salary is : <c:out value="${salary}"/></p>
<c:choose>
    <c:when test="${salary <= 0}">
       Salary is very low to survive.
    </c:when>
    <c:when test="${salary > 1000}">
        Salary is very good.
    </c:when>
    <c:otherwise>
        No comment sir...
    </c:otherwise>
</c:choose>

JSP處理機制

作用域對象

Page > Request > Session > Application的查找,其實相當於依次調用:

  1. pageContext.getAttribute("blog")
  2. request.getAttribute("blog")
  3. session.getAttribute("blog")
  4. application.getAttribute("blog")

一個變量能找到,是因為之前調用了對應的setAttribute()方法進行了設置

簡單來理解一下這四個作用域,一個變量所在的作用域越在後面,存活的時間就越長

  • pageContext對應於一個頁面
  • request對應於一個請求,一個請求是可以包含幾個頁面的(比如使用了includeforward等操作)
  • session對應於一個會話(一般是一個用戶產生一個會話),在會話中會產生多個請求
  • application對應於整個Web應用,一個Web應用匯產生很多會話,所以application中的屬性會在整個應用的生命週期存在

JSP內置對象

EL隱式對象

JSP生命週期

A Java Server Page life cycle is defined as the process started with its creation which later translated to a servlet and after ward servlet lifecycle comes into play. This is how the process goes on until its destruction.

  1. Translation of JSP page to Servlet
  2. Compilation of JSP page (Compilation of JSP into test.java)
  3. Classloading (test.java to test.class)
  4. Instantiation (Object of the generated Servlet is created)
  5. Initialization (jspInit() method is invoked by the container)
  6. Request processing (_jspService() is invoked by the container)
  7. JSP Cleanup (jspDestroy() method is invoked by the container)

We can override jspInit(), jspDestroy() but we cannot override _jspService() method