JSP之 動態包含<jsp:include />
現在我們來看看JSP 的動態包含指令: <jsp:include />
我們建立一個工程TestInclude
然後加入檔案:
Index.jsp:
<%@ page language="java"import="java.util.*" pageEncoding="ISO-8859-1"%><html> <body> <jsp:include page="curDate.jsp?user=ken"/> <p>index.jsp'srequest: <%out.println(request);%> </p> </body></html>
curDate.jsp:
<%@ page language="java"import="java.util.*" %><p>curDate.jsp: <%=new Date()%></p> <!-- curDate--><%= request.getParameter("user") %><p>curDate.jsp's request: <%out.println(request);%> </p>
查看結果/原始碼:
查看Tomcat 工作目錄:
查看index_jsp.java檔案:
try { response.setContentType("text/html;charset=ISO-8859-1"); 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\n"); out.write("<html>\r\n"); out.write(" <body>\r\n"); out.write(" \t"); org.apache.jasper.runtime.JspRuntimeLibrary.include(request,response, "curDate.jsp?user=ken", out, false); out.write("\r\n"); out.write(" \t<p>index.jsp's request: ");out.print(request); out.write(" </p>\r\n"); out.write(" </body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) {
curDate_jsp.java:
try { response.setContentType("text/html"); 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\n"); out.write("<p>curDate.jsp: "); out.print(new Date()); out.write("</p> <!-- curDate -->\r\n"); out.print( request.getParameter("user") ); out.write("\r\n"); out.write("<p>curDate.jsp's request: ");out.print(request); out.write(" </p>");} catch (java.lang.Throwable t) {
在index_jsp.java檔案中
我們看到的<jsp:include page="curDate.jsp?user=ken"/>實際被編譯成以下語句:
org.apache.jasper.runtime.JspRuntimeLibrary.include(request,response,"curDate.jsp?user=ken", out, false);
這個是動態地將參數 (request, response, "curDate.jsp?user=ken",out, false);傳遞到curDate_jsp. java裡執行,注意這些參數在實際程式中是動態,所以當執行這個語句時,curDate_jsp.class 返回結果給index_jsp.class,而這個結果是存放在參數中的對象out中的..簡單地說就是
curDate.jsp取得參數並計算出結果後,再將結果返回給index.jsp(在運行時動態調用的)