SpringMVC从Controller跳转到还有一个Controller

1. 需求背景
    需求:spring MVC框架controller间跳转,需重定向。有几种情况:不带參数跳转。带參数拼接url形式跳转,带參数不拼接參数跳转,页面也能显示。

本来以为挺简单的一件事情。而且个人觉得比較经常使用的一种方式,一百度全都有了,这些根本不是问题,可是一百度竟然出乎我的意料,一堆都不是我想要的结果。无奈啊。自己写一篇比較全都供以后大家一百度吧,哈哈哈。。。

是这些写的不是非常全都人们给了我写这篇博客的动力。 2. 解决的方法 需求有了肯定是解决的方法了,一一解决,说明下spring的跳转方式非常多非常多。我这里仅仅是说一些自我觉得好用的。经常使用的。spring分装的一些类和方法。 (1)我在后台一个controller跳转到还有一个controller,为什么有这样的需求呢,是这样的。我有一个列表页面,然后我会进行新增操作,新增在后台完毕之后我要跳转到列表页面,不须要传递參数,列表页面默认查询全部的。 方式一:使用ModelAndView return new ModelAndView("redirect:/toList"); 这样能够重定向到toList这种方法 方式二:返回String return "redirect:/ toList "; 其他方式:其他方式还有非常多,这里不再做介绍了,比方说response等等。

这是不带參数的重定向。

(2)另外一种情况,列表页面有查询条件。跳转后我的查询条件不能丢掉,这样就须要带參数的了,带參数能够拼接url 方式一:自己手动拼接url new ModelAndView("redirect:/toList?param1="+value1+"¶m2="+value2); 这样有个弊端,就是传中文可能会有乱码问题。 方式二:用RedirectAttributes,这个是发现的一个比較好用的一个类 这里用它的addAttribute方法。这个实际上重定向过去以后你看url,是它自己主动给你拼了你的url。

用法: attr.addAttribute("param", value); return "redirect:/namespace/toController"; 这样在toController这种方法中就能够通过获得參数的方式获得这个參数,再传递到页面。

过去的url还是和方式一一样的。 (3)带參数不拼接url页面也能拿到值(重点是这个) 一般我预计重定向到都想用这样的方式: @RequestMapping("/save") public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr) throws Exception { String code = service.save(form); if(code.equals("000")){ attr.addFlashAttribute("name", form.getName()); attr.addFlashAttribute("success", "加入成功!"); return "redirect:/index"; }else{ attr.addAttribute("projectName", form.getProjectName()); attr.addAttribute("enviroment", form.getEnviroment()); attr.addFlashAttribute("msg", "加入出错!错误码为:"+rsp.getCode().getCode()+",错误为:"+rsp.getCode().getName()); return "redirect:/maintenance/toAddConfigCenter"; } } @RequestMapping("/index") public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr) throws Exception { return "redirect:/main/list"; } 页面取值不用我说了吧,直接用el表达式就能获得到。这里的原理是放到session中,session在跳到页面后立即移除对象。所以你刷新一下后这个值就会丢掉。 3. 总结 最底层还是两种跳转,仅仅是spring又进行了封装而已,所以说跳转的方式事实上有非常多非常多种,你自己也能够封一个。也能够用最原始的response来,也没有问题。好了。就到这儿。

事实上也没有什么,可是知道了这个就非常easy了,之前没搞懂。如今搞懂了,和大家分享。

有问题的给我留言。


原文地址:https://www.cnblogs.com/lcchuguo/p/5401597.html