struts2中 重定向

    技术2022-05-20  38

    struts2中 重定向

     

    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 这个结果。

     

    个人认为:由于大家极度抱怨“action臃肿”,所以struts2中尽量减少了action中的代码。

     


    最新回复(0)