1. 程式人生 > >標準標籤、<jsp:include>、<jsp:forward>

標準標籤、<jsp:include>、<jsp:forward>

使用方法
  標準標籤在jsp頁面直接編寫即可,因為標準標籤是JSP規範提供的,所有容器都支援。

被替代性
  標準標籤的許多功能都可以被JSTL與EL表示式語言所替代。

作用
  標準標籤可協助編寫JSP時減少Scriptlet的使用。

語法
  所有標準標籤都使用jsp:作為前置。


標準標籤<jsp:include>

  和include指示元素對比:
  include指示元素,可以在JSP轉譯為Servlet時,將另一個JSP包括進來進行轉譯,這是靜態地包括另一個JSP頁面,也就是被包括的JSP與原JSP合併在一起,轉譯為一個Servlet類,你無法在執行時依條件動態地調整想要包括的JSP頁面。
  <jsp:include>標籤可以在執行時,依條件動態地調整想要包括的JSP頁面,當前jsp會生成一個Servlet類,被包含的jsp也會生成一個Servlet類。

Demo

index.jsp

在index.jsp中使用了<jsp:param>標籤,指定了傳遞給add.jsp的請求引數。

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<jsp:include page="add.jsp">
    <jsp:param name="a" value="1"/>
    <jsp:param name="b" value="2"/>
</jsp:include>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
</body>
</html>
View Code

add.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" isErrorPage="true" %>
<%@page import="java.io.PrintWriter" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>加法網頁</title>
</head>
<body>
    <%
        String a 
= request.getParameter("a"); String b = request.getParameter("b"); %> <p>a + b = <%=a + b %></p> </body> </html>
View Code

測試地址:http://127.0.0.1/index.jsp

響應結果:a + b = 12

檢視轉譯後的servlet

檢視index_jsp.java的原始碼有如下程式碼:

      org.apache.jasper.runtime.JspRuntimeLibrary.include(
              request, 
              response, 
              "add.jsp" + "?" 
                      + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("a", request.getCharacterEncoding()) 
                      + "="
                      + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("1", request.getCharacterEncoding())
                      + "&" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("b", request.getCharacterEncoding()) 
                      + "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("2", request.getCharacterEncoding()), out, false);
View Code

上面的原始碼其實就是取得RequestDispatcher物件,並執行include()方法。


<jsp:forward>標籤

  將請求轉發給另一個JSP處理。
  同樣地,當前頁面會生成一個Servlet,而被轉發的add.jsp也會生成一個Servlet。
  只要把上面index.jsp裡的include改為forward即可。

檢視index_jsp.java的原始碼有如下程式碼:

      if (true) {
        _jspx_page_context.forward("add.jsp" + "?" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("a", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("1", request.getCharacterEncoding()) + "&" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("b", request.getCharacterEncoding())+ "=" + org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("2", request.getCharacterEncoding()));
        return;
      }
View Code

這裡的原始碼其實就是取得RequestDispatcher物件,並執行forward()方法。

pageContext隱式物件具有forward()與include()方法。