最近发现一个问题,就是使用用户名和密码的方式提交一个表单,提交后页面正常返回视图响应,在session过期后,直接刷新页面,发现用户名和密码还存在。WTF,我真是XTM了。
application.yml 中设置的session超时如下:
server: port: 8085 servlet: session: timeout: PT120S
代表session有效期为120秒
index.html如下:
扫描二维码关注公众号,回复:
6162498 查看本文章
<form action = "/login" method= "post"> <input type="text" name = "username" /> <input type="password" name = "password" /> <input type="submit" value="登录"> </form>
拦截器代码如下:
@Configuration public class LoginInterceptor implements HandlerInterceptor { @Override // 在执行目标方法之前执行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("------:进来拦截器了!--1"); //获取session HttpSession session = request.getSession(false); //取session用false,存session用true,默认true //判断session是否为空,不存在就跳转到登录界面 if(session == null){ System.out.println("session失效了------:跳转到登录页面!"); response.sendRedirect(request.getContextPath()+"/"); return false; }else{ System.out.println("session未失效----------:不用再登录"); System.out.println("session有效期是:---->"+session.getMaxInactiveInterval()); return true; } }
第一次的LoginController如下:
@RequestMapping("/login") public ModelAndView index(ModelMap map,HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView(); String username=request.getParameter("username"); String password=request.getParameter("password"); boolean a = false; if(username!=null && password!=null){ System.out.println("------>用户名和密码不为空"); System.out.println("username--:"+username+"pwd---:"+password); a = hzadminservice.isExist(username, password); } if(a==true){ System.out.println("-------->查询用户成功!"); request.getSession().setAttribute("username", username); // 将用户信息放入session map.addAttribute("username",username); mv.setViewName("front"); }else{ System.out.println("-------->用户不存在,返回失败页面"); mv.setViewName("fail"); } }
在这种情况下,当登录成功后返回的是front.html页面,没错,但是当超过120秒之后,我刷新页面,问题来了,用户名和密码依然存在,导致我刷新又重新看到了front.html页面,并没有返回到登录页。控制台打印如下:
------:进来拦截器了!--1 session未失效----------:不用再登录 session有效期是:---->120
按理说session失效后如果你刷新页面应该在拦截器中发生跳转,回到登录页,但是并没有。
没办法,百度,网上看到一个解决办法https://blog.csdn.net/skyjian10/article/details/79192144
让页面重定向即可解决,于是我把LoginController改了
第二次的LoginController如下:
@RequestMapping("/login") public String index(ModelMap map,HttpServletRequest request, HttpServletResponse response) { String username=request.getParameter("username"); String password=request.getParameter("password"); boolean a = false; if(username!=null && password!=null){ System.out.println("------>用户名和密码不为空"); System.out.println("username--:"+username+"pwd---:"+password); a = hzadminservice.isExist(username, password); } if(a==true){ System.out.println("-------->查询用户成功!"); request.getSession().setAttribute("username", username); // 将用户信息放入session return "redirect:/front"; }else{ System.out.println("-------->用户不存在,返回失败页面"); return "fail"; }
运行,等待120秒后,此时直接刷新,发现回到了登录页。问题解决!