springmvc怎么重定向,从一个controller跳到另一个controller

来源:互联网 发布:淘宝联盟用店铺红包 编辑:程序博客网 时间:2024/05/18 01:11

前言:

有作者写出了部分方法,但没有给出具体实践,小白看后云里雾里,我这里做两件事:1 给出具体代码 2 对已经有的方法给出补充。

参考:http://my.oschina.NET/u/1866821/blog/509054?fromerr=gT7zS0oS

第一种情况,不带参数跳转:

方法一:方式一:使用ModelAndView
        return new ModelAndView("redirect:/toList");
        这样可以重定向到toList这个方法

方法二:在return后直接,redirect 加上要跳转的地址,即可以从第一个controller跳到第二个controller,如下图代码中方法一

方法三:见蓝色框,只要在return后直接加想要跳到的controller的方法名即可,注意,这个方法名不是RequestMapping里影射的路径,是controller里具体的方法,

如图片中的3和4,走完3后,他会找到4而不是2(2是RequestMapping里映射的路径),这个像不像Java方法的重载,如下图代码中方法二


2015-12-10今天暂时写到这里!


第二种情况,带参数跳转

方法一:直接在后面用?拼接如图。




方式二:用RedirectAttributes,这个是发现的一个比较好用的一个类
                    这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
                    使用方法:

                     attr.addAttribute("param", value);
                    return "redirect:/namespace/toController";
                    这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。过去的url还是和方式一一样的。

方法三:带参数不拼接url页面也能拿到值(重点是这个)


[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1.          @RequestMapping("/save")  
  2.     public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)  
  3.                    throws Exception {  
  4.   
  5.   
  6.         String code =  service.save(form);  
  7.         if(code.equals("000")){  
  8.             attr.addFlashAttribute("name", form.getName());    
  9.             attr.addFlashAttribute("success", "添加成功!");  
  10.             return "redirect:/index";  
  11.         }else{  
  12.             attr.addAttribute("projectName", form.getProjectName());    
  13.             attr.addAttribute("enviroment", form.getEnviroment());    
  14.             attr.addFlashAttribute("msg", "添加出错!错误码为:"+rsp.getCode().getCode()+",错误为:"+rsp.getCode().getName());  
  15.             return "redirect:/maintenance/toAddConfigCenter";  
  16.         }  
  17.     }  
  18.   
  19.   
  20. @RequestMapping("/index")  
  21.        
  22.   
  23.     public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)  
  24.                    throws Exception {  
  25.             return "redirect:/main/list";  
  26.     }  
  27. //页面取值,直接用el表达式就能获得到,这里的原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉。  
  28. //3. 最底层还是两种跳转,只是spring又进行了封装而已,所以说跳转的方式其实有很多很多种,你自己也可以封一个,也可以用最原始的response来,也没有问题。好了,//就到这儿。 其实也没有什么,但是知道了这个就很简单了,之前没搞懂,现在搞懂了,和大家分享。有问题的给我留言。  
[html] view plain copy
  1.   


报错:用RedirectAttributes可能会报错

错误信息:java.lang.IllegalStateException: Argument [RedirectAttributes] is oftype Model

解决:

1 RedirectAttributes这个是spring3.1.x以上才有的,保证版本高于3.1

2 http://201205083157.iteye.com/blog/1525180

0 0