后台控制用户登录的信息
@Controller
public class AdminController {
@RequestMapping({"/index", "/"})
public String index(){
return "index";
}
@PostMapping("/login")
public String login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpSession session,
HttpServletRequest request){
System.out.println("用户名:" + userName);
System.out.println("密码:" + password);
request.getSession().setAttribute("userId", 1);
session.setAttribute("msg", "session中的属性msg");
request.setAttribute("ver", "request中的属性ver");
return "redirect:/success";
}
@RequestMapping("/success")
public String successPage(){
return "success";
}
}
index.html页面
<form th:action="login" method="post">
用户名:<input type="text" name="userName"></br>
密码:<input type="password" name="password"></br>
<input type="submit" value="登录">
</form>
<h1 th:text="${session.msg}"></h1>
success.html页面
<h1>登录成功</h1>
<div th:text="${session.userId}"> </div>
<div th:text="${session.msg}">hhhh</div>
<div th:text="${#httpServletRequest.getAttribute('ver')}">hhhh</div>
<div th:text="${#httpServletRequest.getAttribute('userName')}">hhhh</div>
<div th:text="${#httpServletRequest.getAttribute('interceptor')}">hhhh</div>
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行。。。");
HttpSession session = request.getSession();
if(session.getAttribute("userId") != null){
request.setAttribute("interceptor", "拦截器已经检验!!!");
return true;
}
request.getSession().setAttribute("msg", "请先登录!!");
request.getRequestDispatcher(request.getContextPath() + "/index").forward(request, response);
return false;
}
}
整个浏览器的大致运行过程
当后台login方法中
return “redirect:/success”;
则代表重定向,
在request中保存的属性页面获取不到
如下如所示:
当后台login方法修改为
return “forward:/success”;
前端页面显示如下:
通过对比可以发现request中保存的属性值可以获取了。
如果大家仔细观察拦截器中的代码,会发现request对象中也存放了属性,而且两种方式都能够获取到“拦截器已经检验”的信息。
这个请求转发会出现我就不解释了,主要解释为什么重定向会出现这种状况。
主要是因为在login方法中request对象中保存的属性,在经过重定向后, 这个对象消失了,会产生一个新的request对象,所以login方法中的属性获取不到,客户端会重新发送请求,但是会被拦截器拦截, 之后拦截器里面的request对象并没有消失。