项目场景:
一个普通的登录界面,成功后重定向到主页
问题描述:
重定向后在前端代码无法使用thymeleaf来调取session中的数据
@PostMapping(value = "/user/login")
public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map,HttpSession session){
System.out.println(password);
Subject subject= SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(username,password);//可以理解为一个存放账号密码的容器
try {
subject.login(token);
} catch (UnknownAccountException e){ //用户名不存在
map.put("msg","用户名错误");
return "/login.html";
}catch (IncorrectCredentialsException e){//密码错误
map.put("msg","密码错误");
return "/login.html";
}
session.setAttribute("msg",username);
return "redirect:/index.html";
}
原因分析:
应为在重定向后无法获取cookie的请求头所以会导致无法获取session
解决方案:
我们可以在同一Controller中创建一个中转,通过中转获取存储在服务器的session,通过转发的方式来跳转到界面
@PostMapping(value = "/user/login")
public String Login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map,HttpSession session){
System.out.println(password);
Subject subject= SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(username,password);//可以理解为一个存放账号密码的容器
try {
subject.login(token);
} catch (UnknownAccountException e){ //用户名不存在
map.put("msg","用户名错误");
return "/login.html";
}catch (IncorrectCredentialsException e){//密码错误
map.put("msg","密码错误");
return "/login.html";
}
session.setAttribute("msg",username);
return "redirect:/index.html";
}
@RequestMapping(value = "/index.html")
public String indexRd(HttpSession session,Map<String,String> map){
map.put("msg", (String) session.getAttribute("msg"));
return "/index.html";
}