RedirectAttribute对象传参

因为thymeleaf遵守MVC规范,请求如果需要重定向,则需要先重定向到controller方法中
再通过转发的方式,跳转到html页面上,在这种情况下,RedirectAttribute用于重定向传递参数。

在控制器方法参数中使用RedirectAttribute对象,这个对象传递参数有两个方法

  • addAttribute方法

    @Controller
    public class LoginController {
        @RequestMapping("/login")
        public String login(RedirectAttributes redirectAttributes){
            ......
            redirectAttributes.addAttribute("loginResult","登录失败");
            return "redirect:/toIndexHtml";
        }
    
        @RequestMapping("/toIndexHtml")
        public String index(){
            return "index";
        }
    }

    如果使用这种方式,则重定向后,页面url上会显示参数信息,并不安全,例如显示如下

    "http://localhost:8080/toIndexHtml?loginResult=登录失败"

    并且,这种方式前端thymeleaf使用[[${loginResult}]],或者jsp使用EL表达式都不能获取到值
    如果想让前端获取到值,你需要在index方法参数中使用@ModelAttribute注解,即如下:

    @RequestMapping("/toIndexHtml")
    public String index(@ModelAttribute("loginResult")String loginResult){
        return "index";
    }

    其原理是:当重定向时,即第二次请求执行index方法时,该注解将携带的第一次请求所返回的loginResult
    数据保存在隐含模型中,并最终放入request域中,最后转发,并被视图渲染出来

  • addFlashAttribute

    //主要部分,其他代码和上面一样
    redirectAttributes.addFlashAttribute("loginResult","登录失败");
    return "redirect:/toIndexHtml";

    使用这种方式,并不需要在toIndexHtml使用@ModelAttribute注解才能使得前端获取到传递的loginResult
    数据,该方式的原理是重定向时,redirectAttributes对象会将数据保存在一个临时的session中
    并返回一个JSESSIONID,在第二次请求访问index方法时,底层将该session数据取出放入request域
    中,并删除该临时session,所以这种方式无需使用@ModelAttribute注解就可使得前端同样获取到数据。
    当然,你还是可以在index方法参数中使用@ModelAttribute注解,从而在index方法中对数据进行处理

  • 总结:RedirectAttribute用于重定向时传递参数,

    • 如果使用该对象的addAttribute方法传递数据,则需要在跳转页面的controller方法(index方法)
      参数上使用@ModelAttribute注解,将第二次请求携带的loginResult数据保存至request域中,
      即可使前端获取到数据
    • 如果使用该对象的addFlashAttribute方法传递数据,则不需要使用ModelAttribute注解,也能使得前端
      获取到数据,当然你也可以使用该注解,从而在index方法中使用传递的数据。