struts2 的重定向和struts1 在使用方法上有所不同。
如在一個(gè)登錄的action中驗(yàn)證成功后,重定向?yàn)轱@示用戶信息的action: showInfo.do
一、在struts1 中實(shí)現(xiàn):
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//一些處理……
//重定向
ActionForward forward = new ActionForward("showInfo.do");
forward.setRedirect(true);
return forward ;
}
}
二、在struts2 中,因?yàn)閳?zhí)行函數(shù)返回結(jié)果不再是ActionForward ,而是一個(gè)字符串,所以不能再像struts1中那樣跳轉(zhuǎn)了。
在struts2中,重定向要在struts.xml中配置:
<action name="login" class="LoginAction">
<result name="success" type="velocity">/pages/logok.vm</result>
<result name="redirect_1" type="redirect">showInfo.do</result>
<result name="redirect_2" type="redirect">showInfo.do?name=yangzi</result>
<result name="redirect_3" type="redirect">showInfo.do?name=${name}</result>
<result name="redirect_4" type= "redirect">
<param name="actionName">showInfo</param>
<param name="name">${name}</param>
</result>
</action>
對(duì)應(yīng)的LoginAction:
public class LoginAction extends ActionSupport{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() throws Exception {
//一些處理……
name=xiaowang ; //給要傳遞的參數(shù)賦值
return SUCCESS; //默認(rèn)頁(yè)面
//return "redirect_1" ; //重定向(不帶參數(shù)) showInfo.do
//return "redirect_2" ; //重定向(帶固定參數(shù)yangzi) showInfo.do?name=yangzi
//重定向(帶動(dòng)態(tài)參數(shù),根據(jù)struts.xml的配置將${name}賦值為xiaowang)最后為 showInfo.do?name=xiaowang
// return "redirect_3" ;
//return "redirect_4" ; //這個(gè)是重定向到 一個(gè)action
}
}
三、說(shuō)明
struts2 重定向分重定向到url和重定向到一個(gè)action。
實(shí)現(xiàn)重定向,需在struts.xml中定義返回結(jié)果類型。
type="redirect" 是重定向到一個(gè)URL。type="redirect-action" 是重定向到一個(gè)action。
參數(shù)也是在這里指定,action中所做的就是給參數(shù)賦值,并return 這個(gè)結(jié)果。
個(gè)人認(rèn)為:由于大家極度抱怨“action臃腫”,所以struts2中盡量減少了action中的代碼。
轉(zhuǎn)載:
http://hi.baidu.com/myfreeint/blog/item/d5f42e0122b9a8031c958341.html