没用的话就不说了,像什么RedirectAttributes 是Spring mvc 3.1版本之后出来的一个功能,专门用于重定向之后还能带参数跳转的的工具类,网上一大堆!
来看看问题!
后端代码
@PostMapping("/dologin")
public String dologin(RedirectAttributes redirectAttributes){
redirectAttributes.addAttribute("error","我是错误信息");
return "redirect:/login";
}
界面取值
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/dologin" method="post">
<ul>
<li class="top_1">
<span style="color:red">[[${error}]]</span>
<input type="text" name="username" placeholder=" 邮箱/用户名/已验证手机" class="user" />
</li>
<li>
<input type="password" name="password" placeholder=" 密码" class="password" />
</li>
<li class="ent"><button type="submit" class="btn2"><a>登 录</a></button></li>
</ul>
</form>
</body>
</html>
跑起来界面效果!
哈哈,TMD值[[${error}]]取不出来???!!!
这里使用EL表达式是取不到值得,不信可以试试,这里也不是完全取不到值,可以使用JS来获取URL上的参数,那么这样是能取到值的,网上很多博客都只展示了后端JAVA代码,往往很多人都只在意这一句代码
redirectAttributes.addAttribute("error", "我是错误信息");
然后前端使用EL表达式疯狂的试探,也没试探出个啥玩意,就像我上面的演示代码和界面效果一样!记住addAttribute是无法使用EL表达式取值的!如果非要使用addAttribute重定向带值并且前端取值的话,前端那就只能使用JS取URL上的值了
在这里插入代码片
RedirectAttributes还提供了另一个方法,也能从重定向带值,我们修改一下代码试试看!
后端代码
@PostMapping("/dologin")
public String list(RedirectAttributes redirectAttributes, Model model){
redirectAttributes.addFlashAttribute("error","我是错误信息");
return "redirect:/";
}
前端代码不动
运行看看效果
诶,这个redirectAttributes.addFlashAttribute(“error”,“我是错误信息”);Html界面上使用EL表达式能取到!而且URL上也没有值了!!!
详细介绍对比一下二者的区别
redirectAttributes.addAttributie(“prama”,value);
这种是等同于return:"redirect:/path/list?prama1=value1&prama2=value2 ",注意这种方法直接将传递的参数暴露在链接地址上,是不安全的,慎用。
redirectAttributes.addFlashAttributie(“prama”,value);
这种方法是隐藏了参数,链接地址上不直接暴露,但是能且只能在重定向的 “页面” 获取prama参数值。其原理就是放到session中,session在跳到页面后马上移除对象。如果是重定向一个controller中是获取不到该prama属性值的。除非在controller中用(@RequestParam(value = “prama”)String prama)注解,采用传参的方式。页面获值例
@PostMapping("/dologin")
public String list(RedirectAttributes redirectAttributes, Model model){
redirectAttributes.addAttribute("error","我是错误信息");
redirectAttributes.addFlashAttribute("flashError","我是FlashError错误信息");
return "redirect:/redTest";
}
@GetMapping("/redTest")
public String redTest(@RequestParam("error") String error){
System.out.println("error"+error);
System.out.println("flashError"+error);
return "login";
}