理解JSP中的include(一):include-file 指令測試
來源:互聯網
上載者:User
include|js 第一個例子:
include-file-test-1.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<%! String dec_str = "dec_str";%>
<%=dec_str%><br>
<%@ include file="include-file-test-2.jsp" %><br>
<%=dec_str%><br>
include-file-test-2.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<%
dec_str = "scr_str"; //Eclipse顯示出錯。
%>
結果:
dec_str
scr_str
結論:file1中定義的執行個體變數(或局部變數),file2可以引用並更改。但直接存取file2會出錯。
第二個例子:
include-file-test-1.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<% scr_str = "hello " + scr_str;%>
<%@ include file="include-file-test-2.jsp" %>
<%=scr_str%><br>
<% temp = "hello " + temp;%>
<%=temp%>
include-file-test-2.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<%! String scr_str = "scr_str";%>
<% String temp = "temp"; %>
查看file1 對應的servlet:
package org.apache.jsp.jsp_002dsyntax_002dtest;
import ……;
public final class include_002dfile_002dtest_002d1_jsp …… {
String scr_str = "scr_str";
private static java.util.Vector _jspx_dependants;
static {
_jspx_dependants = new java.util.Vector(1);
_jspx_dependants.add("/jsp-syntax-test/include-file-test-2.jsp");
}
public java.util.List getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
……
try {
……
response.setContentType("text/html;charset=GBK");
……
scr_str = "hello " + scr_str;
String temp = "temp";
……
out.print(scr_str);
temp = "hello " + temp;
……
out.print(temp);
} catch (Throwable t) {
……
} finally {
……
}
}
}
結果:
hello scr_str
hello temp
結論:file2中定義的執行個體變數,file1可以在<%@ include file="" %>指令之前(或之後)引用並更改。
file2中定義的局部變數,file1必須在<%@ include file="" %>指令之後引用並更改。
第三個例子:
include-file-test-1.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<%!
String str1 = "str1 ";
%>
<%
String str4 = str1 + str2 + str3;
%>
<%@ include file="include-file-test-2.jsp" %>
<%=str4%>
include-file-test-2.jsp:
<%@ page contentType="text/html;charset=GBK" %>
<%!
String str2 = "str2 ";
String str3 = str1 + str2;
%>
file1對應的servlet:
package org.apache.jsp.jsp_002dsyntax_002dtest;
import ……
public final class include_002dfile_002dtest_002d1_jsp ……{
String str1 = "str1 ";
String str2 = "str2 ";
String str3 = str1 + str2;
……
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
……
try {
……
response.setContentType("text/html;charset=GBK");
……
String str4 = str1 + str2 + str3;
……
out.print(str4);
} catch (Throwable t) {
……
}
結果:
str1 str2 str1 str2
結論:file2並不產生servlet,但其中的內容都被包含在了file1產生的servlet之中;file2本身也被添加進名為“ _jspx_dependants”的Vector類型的類變數中。可以看到,在file2中定義的執行個體變數“scr_str ”被轉移到了file1產生的servlet中。可見Tomcat是以一種很耐人尋味的機制進行處理的。