SpringMVC中controller的跳转

controller中的重定向

  (1)不需要传递参数重定向


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

        方式二:返回String
    return "redirect:/ toList "; 

    (2)第二种情况,列表页面有查询条件,跳转后我的查询条件不能丢掉,这样就需要带参数的了,带参数可以拼接url

        方式一:自己手动拼接url

                    new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2);
                    这样有个弊端,就是传中文可能会有乱码问题。

 

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

                     attr.addAttribute("key", value);

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

    

原文地址:https://www.cnblogs.com/miye/p/7682566.html