struts重定向

来源:互联网 发布:查看内存软件 编辑:程序博客网 时间:2024/05/21 11:06
struts2 的重定向和struts1 在使用方法上有所不同。  微笑微笑微笑
如在一个登录的action中验证成功后,重定向为显示用户信息的action: showInfo.do 
一、在struts1 中实现: 
 
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 中,因为执行函数返回结果不再是ActionForward ,而是一个字符串,所以不能再像struts1中那样跳转了。

 在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> 


对应的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  //给要传递的参数赋值    

      return SUCCESS;   

      //默认页面  return "redirect_1" 

      //重定向(不带参数)  showInfo.do  

      //return "redirect_2"  

      //重定向(带固定参数yangzi) showInfo.do?name=yangzi 

      //重定向(带动态参数,根据struts.xml的配置将${name}赋值为xiaowang)最后为 showInfo.do?name=xiaowang       // return "redirect_3"  

     //return "redirect_4"  //这个是重定向到 一个action } } 

三、说明 

 
struts2 重定向分重定向到url和重定向到一个action。 实现重定向,需在struts.xml中定义返回结果类型。 
type="redirect" 是重定向到一个URL。type="redirect-action" 是重定向到一个action。 
参数也是在这里指定,action中所做的就是给参数赋值,并return 这个结果。