先寫兩個概念:
forward(轉發):
1、forward是服務器跳轉,瀏覽器不知道它所請求的具體資源來源,瀏覽器的地址欄不會變;
2、request.getRequestDispatcher("test.jsp").forward(request, response);//轉發到test.jsp
3、以前的request中存放的變量不會失效,就像把兩個頁面拼到了一起;
4、轉發頁面和轉發到的頁面可以共享request裏面的數據。
redirect(重定向):
1、 redirect,服務端根據邏輯,發送一個狀態碼,告訴瀏覽器重新去請求那個地址.所以地址欄顯示的是新的URL;
2、response.sendRedirect("test.jsp");//重定向到test.jsp
3、以前的request中存放的變量全部失效,並進入一個新的request作用域;
4、redirect,不能共享數據。
structs.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="resultTypes" namespace="/r" extends="struts-default">
<!-- result如果不指定type,默認是dispatcher,也就是forward(跳轉)到一個文件去 -->
<action name="r1">
<result type="dispatcher">/r1.jsp</result>
</action>
<action name="r2">
<result type="redirect">/r2.jsp</result>
</action>
<action name="r3">
<result type="chain">r1</result>
</action>
<action name="r4">
<result type="redirectAction">r2</result>
</action>
</package>
</struts>
index.jsp:
<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<% String context = request.getContextPath(); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>Insert title here</title>
</head>
<body>
Result類型
<ol>
<li><a href="r/r1">dispatcher</a>:服務器跳轉,只能跳轉到頁面,html,jsp,freemarker等</li>
<li><a href="r/r2">redirect</a>:客戶端跳轉視圖</li>
<li><a href="r/r3">chain</a>:forward到另一個action</li>
<li><a href="r/r4">redirectAction</a>:客戶端跳轉</li>
<li>freemarker</li>
<li>httpheader</li>
<li>stream</li>
<li>velocity</li>
<li>xslt</li>
<li>plaintext</li>
<li>tiles</li>
</ol>
</body>
</html>
頁面如圖所示:
項目結構如圖: