JSP 文法基礎知識(二),jsp文法基礎知識
1. 指令<%@ %>
(1)page 指令
通過設定內部的多個屬性來定義整個頁面的屬性
文法:<%@ page 屬性1="屬性值" 屬性2="屬性值1,屬性值2"… 屬性n="屬性值n"%>
page 指令常用屬性 :
例如:<%@ page language="java" contentType="text/html;charset=GBK"%>
(2) include 指令
包含操作可以將一些重複的程式碼封裝含進來繼續使用。此種包含稱作“靜態包含”。
文法:<%@include file="要包含的檔案路徑"%>
例如:
<h1>靜態包含操作</h1>
<%@ include file=include1.jsp"%>
<jsp:include/>
2.JSP 標準動作
(1)<jsp:include/>
可以把其他檔案包含進來,此種包含為動態包含
文法:
不傳遞參數:<jsp:include page="{要包含的檔案路徑}"/>
傳遞參數
<jsp:include page="{要包含的檔案路徑}">
<jsp:param name = "參數名稱 1" value = "參數內容 1"/>
<jsp:param name = "參數名稱 2" value = "參數內容 2"/>
...可以向被包含頁面中傳遞多個參數
</jsp:include>
(2)靜態包含與動態包含區別
靜態包含:
include1.jsp頁面
<span style="font-size:18px;"><%int x = 10 ;%><h1>被包含頁面:include1.jsp--<%=x%></h1></span>
include2.jsp頁面
<span style="font-size:18px;"><%@ page contentType="text/html" pageEncoding="GBK"%><html><head><title>靜態包含</title></head><body><%int x = 100 ; // 變數重複%><h1>include2.jsp -- <%=x%></h1><%@include file="include1.jsp"%></body></html></span>
程式運行時出現 500 的 HTTP 狀態代碼,屬於伺服器錯誤,x 被重複定義了。在觀察 JSP
引擎編譯得到的 Java 檔案:只產生了一個 java 檔案。所以,靜態包含採用先包含後處
理的形式。
動態包含:
<span style="font-size:18px;"><%@ page contentType="text/html" pageEncoding="GBK"%><html><head><title>動態包含</title></head><body><%int x = 100 ; // 變數重複%><h1>include3.jsp -- <%=x%></h1><jsp:include page="include1.jsp"/></body></html></span>
程式運行沒有錯誤,動態包含如果包含的是動態網頁面,採用先處理後包含形式。
3. <jsp:forward/>
從當前頁面跳轉到指定頁面,跳轉操作屬於伺服器端跳轉,跳轉之後的頁面路徑不
改變
文法:
不傳遞參數
<jsp:forward page = "要包含的檔案路徑">
傳遞參數
<jsp:forward page = "要包含的檔案路徑">
<jsp:param name = "參數名稱" value = "參數內容"/>
...可以向被包含頁面中傳遞多個參數
</jsp:forward>
例如:
forward2.jsp 為跳轉後的頁面
<span style="font-size:18px;"><%@ page contentType="text/html" pageEncoding="GBK"%><h1>這是跳轉之後的頁面</h1><h2>參數一:<%=request.getParameter("name")%></h2><h2>參數二:<%=request.getParameter("info")%></h2></span>
forward1.jsp 發生跳轉的頁面
<pre name="code" class="html"><span style="font-size:18px;"><html><head><title>跳轉動作</title></head><body><%String username = "lcx" ;%><jsp:forward page="forward2.jsp"><jsp:param name="name" value="<%=username%>"/><jsp:param name="info" value="teacher"/></jsp:forward></body></html></span>