首先說明JSP引入文件有兩種方式,分別爲
<%@ include file="FourthJsp.jsp" %>和<jsp:include page="header.jsp"/>兩種,分別是,第一種方式將會在編譯前直接賦值被include的文件內容到當前文件中,然後一起生成一個Servlet;而第二種,將會分別生成兩個不同的Servlet,並且Servlet之間的通信依靠request和response。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FirstJsp</title>
</head>
<body>
<%!
String param1 = null;
String param2 = null;
String param3 = null;
String param4 = null;
%>
<%@ include file="ThirdJsp.jsp" %>
<dr/>
<h1>This is the FirstJsp!!!</h1>
<h4>FirstJsp get params</h4>
<%
param1 =(String) request.getAttribute("param1");
param2 =(String) request.getAttribute("param2");
param3 =(String) request.getAttribute("param3");
param4 =(String) request.getAttribute("param4");
%>
param1: <%=param1 %> <br/>
param2: <%=param2 %> <br/>
param3: <%=param3 %> <br/>
param4: <%=param4 %> <br/>
<%
//request.setAttribute("param4", "param-value-good four!");
param4 = "param-value-good-four!";
%>
<%@ include file="FourthJsp.jsp" %>
第二個JSP文件爲FourthJsp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FourthJsp</title>
</head>
<body>
<h1>This is the FourthJsp!!! Test</h1>
<h4>FourthJsp get params</h4>
param1: <%=param1 %> <br/>
param2: <%=param2 %> <br/>
param3: <%=param3 %> <br/>
param4: <%=param4 %> <br/>
</body>
</html>
輸出爲
This is the ThirdJsp!!!
This is the FirstJsp!!!
FirstJsp get params
param1: param1-value1param2: param1-value2
param3: param1-value3
param4: param1-value4
This is the FourthJsp!!! Test
FourthJsp get params
param1: param1-value1param2: param1-value2
param3: param1-value3
param4: param-value-good-four!
可以看出被include的文件可以直接會使用當前文件中聲明的變量。注意,被包含的文件不能夠對已經聲明的變量進行重新聲明,比如第二個JSP文件改爲如下內容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>FourthJsp</title>
</head>
<body>
<%!
String param1 = null;
String param2 = null;
String param3 = null;
String param4 = null;
%>
<h1>This is the FourthJsp!!! Test</h1>
<h4>FourthJsp get params</h4>
param1: <%=param1 %> <br/>
param2: <%=param2 %> <br/>
param3: <%=param3 %> <br/>
param4: <%=param4 %> <br/>
</body>
</html>
此時將會報錯,報錯內容爲
給出變量重複定義的錯誤!!!