springmvc中controller内方法跳转forward?redirect?

使用springmvc的controller的时候,碰到controller内方法的跳转的问题,记录下问题以及自己测试的过程。

场景:

业务执行更新操作之后返回列表页面,列表页面需默认展示查询的列表数据,涉及到两个controller的跳转。

问题

是使用forward还是redirect跳转

解决问题
其实使用forward或者redirect都能达到目的,但是有些问题在下面说明。
1、使用forward
a、例如:return "forward:/rest/queryData",实际的效果是在浏览器中的url地址还是原地址,存在重复提交的问题,所以forward就不推荐使用了。
b、如果是需要携带参数,直接拼接传递的参数,例如:return "forward:/rest/queryShopAlisName?phone=xxxxxxx"; 在跳转的controller中使用参数【@RequestParam("phone") String phone】获得传递的参数值,显然这样的方式也是不推荐的。

2、使用redirect
在controller方法的参数中使用RedirectAttributes来
a、不带参数:
直接使用 return "redirect:/rest/queryShopAlisName";浏览器的地址变成跳转的新地址,避免了重复提交的问题。
b、带参数的时候:


第一种选择:直接在url后面拼接参数,使用@RequestParam来取值,不推荐使用


第二种选择:在controller方法的参数中使用RedirectAttributes来传递参数

    @RequestMapping(value = "/checkMember")
    public String checkMember(HttpServletRequest request, RedirectAttributes attr) {
            Member member = null;
        try {
            String phone = request.getParameter("phone");
            ***attr.addAttribute("phone", "xxxx");***
            member = cashierService.checkIsMember(phone);
        } catch (Exception e) {
            logger.error("query member is error happen : " + e);
        }
        return "redirect:/rest/queryShopAlisName";
    }

使用attr.addAttribute来设置值,然后在跳转的controller中同样使用@RequestParam来取值,在浏览器中同样是拼接参数的形式,例如:http://localhost:8080/xxxx/xx...,同样不建议这么使用。


第三种选择:使用RedirectAttributes的addFlashAttribute的方法来设置值,原理是在跳转前将值放入session中,跳转之后就将值清除掉。浏览器的地址不显示参数的值,推荐使用这种方法来传值。

attr.addFlashAttribute("phone", "xxxxxxx");

在跳转的controller的参数中增加@ModelAttribute来取得参数值

@RequestMapping(value = "/queryShopAlisName")
    public String queryShopAlisName(@ModelAttribute("phone")String  phone) {
        ......
        return "";
    }

第一次写博客来记录,还请看官多多包涵咯。就这样结束吧

            </div>
原文地址:https://www.cnblogs.com/jpfss/p/9523713.html