@RequestMapping("/user/hello")
public String hello(Model model) {
model.addAttribute("hello","world");
model.addAttribute("hello2","world");
return "test";
}
/**
* 测试thymeleaf
*
*/
@RequestMapping("/testThymeleaf")
public String TestThymeleaf(Model model){
model.addAttribute("username","asdasdas");
return "redirect:/user/hello";
}
对于以上代码,在开发过程中我们可以会遇到很多次,比如在验证后添加提示信息,然后转到登录页面等。今天在整理Shiro的时候,遇到了model数据丢失的情况,就是在重定向后model的数据被清空了?以前一直没有遇到,这里遇到了,就记录一下。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<h3 th:text="${username}"></h3>
进入用户添加功能:<a href="add">用户添加</a>
进入用户更新功能:<a href="update">用户更新</a>
</body>
</html>
预想的结果是:会有一个h3的字符串会显示出来。
但是实际结果:
我们发现,并没有这个字符串,这是为什么呢?
后来debug调试发现,在使用redirect重定向请求后,model的值被清空了,所以造成了model数据丢失的情况。
怎么解决?
@RequestMapping("/login")
public String login(User user, RedirectAttributesModelMap model){
System.out.println(user.toString());
/**
* 使用shiro编写认证操作
*/
//1、获取Subject
Subject subject= SecurityUtils.getSubject();
//2、封装用户数据
UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
//3、执行登陆方法
try {
subject.login(token); // ===>去到ShiroConfig的验证操作
//登陆成功
model.addFlashAttribute("msg","登陆成功");
System.out.println("登陆成功");
return "redirect:testThymeleaf";
}catch (UnknownAccountException e){
//登陆失败:用户名不存在
model.addFlashAttribute("msg","用户名不存在");
System.out.println("用户名不存在");
return "redirect:/to_login";
}catch (IncorrectCredentialsException e){
//登陆失败:密码错误
model.addFlashAttribute("msg","密码错误");
System.out.println("密码错误");
return "redirect:/to_login";
}
}
我们只需要把Model改为RedirectAttributesModelMap 就可以了,这样在重定向后不会丢失model的数据。