forward 動作標籤:
<jsp:forward page=”要轉向的頁面”>
</jsp:forward>
或
<jsp:forward page=”要轉向的頁面”/>
該指令的作用是:從該指令處停止當前頁面的繼續執行,而轉向其他的一個JSP頁面。
在下面例子的JSP頁面中,首先隨機獲取一個數,如果該數大於0.5就轉向頁面example2.jsp,否則轉向fileoutput.jsp
<%@ page contentType="text/html;charset=GB2312"%>
<HTML>
<BODY>
<%
double i=Math.random();
if(i>0.5)
{
%>
<jsp:forward page="example2.jsp"/>
<%
}
else
{
%>
<jsp:forward page="fileoutput.jsp"/>
<%
}
%>
<p>
這句話和下面的表達式的值能輸出嗎?
<%=i%>
</BODY>
</HTML>
example2.jsp
<%@ page contentType="text/html;charset=GB2312"%>
<HTML>
<BODY BGCOLOR=cyan>
<FONT Size=4>
<%!
int i=0;
%>
<%
i++;
%>
<p>您是第
<%=i%>
個訪問本站的客戶。
<p>
</FONT>
</BODY>
</HTML>
fileoutput.jsp
<%@ page contentType="text/html;charset=GB2312"%>
<%@ page import="java.io.*"%>
<HTML>
<BODY BGCOLOR=cyan>
<FONT Size=4>
<%!
int number=0;
File file=new File("count.txt");
synchronized void countPeople()
{
if(!file.exists()){
number++;
try{
file.createNewFile();
FileOutputStream out=new FileOutputStream("count.txt");
DataOutputStream dataOut=new DataOutputStream(out);
dataOut.writeInt(number);
out.close();
dataOut.close();
}catch(IOException ee){}
}
else{
try{
FileInputStream in=new FileInputStream("count.txt");
DataInputStream dataIn=new DataInputStream(in);
number=dataIn.readInt();
number++;
in.close();
dataIn.close();
FileOutputStream out=new FileOutputStream("count.txt");
DataOutputStream dataOut=new DataOutputStream(out);
dataOut.writeInt(number);
out.close();
dataOut.close();
}catch(IOException ee){}
}
}
%>
<%
countPeople();
%>
<p>您是第
<%=number%>
個訪問本站的客戶。
<p>
</FONT>
</BODY>
</HTML>
運行效果: