当前位置:   article > 正文

Java--过滤器LoginFilter实现会话超时跳转登录页面_java filter超时

java filter超时

一、说明

1、网站系统登录,从安全的角度来考虑,登录会话超时,再次页面会退到登录界面。
2、本文配置如何通过过滤器(Filter)实现会话超时(如30分钟)跳转到登录页面,分LoginFilter.java类和web.xml配置两部分。

二、实现代码

过滤器类LoginFilter.java

 

  1. package com.sale.filter;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.http.HttpSession;
  12. /**
  13. * @author 作者:Justin
  14. * @version 创建时间:2018年1月25日 上午10:36:23
  15. * 类说明
  16. */
  17. public class LoginFilter implements Filter {
  18. @Override
  19. public void destroy() {
  20. // TODO Auto-generated method stub
  21. }
  22. @Override
  23. public void doFilter(ServletRequest req, ServletResponse res,
  24. FilterChain chain) throws IOException, ServletException {
  25. HttpServletRequest httpReq=(HttpServletRequest)req;
  26. HttpServletResponse httpRes=(HttpServletResponse)res;
  27. HttpSession httpSession=httpReq.getSession();
  28. String path = httpReq.getRequestURI(); //当前请求相对url
  29. String loginUrl = httpReq.getContextPath()+ "/loginout.action"; //1.登录界面url
  30. String initUrl = httpReq.getContextPath()+ "/tevo_loginInit.action"; //2.初始化界面url
  31. String userName = (String)httpSession.getAttribute("currentUsername"); //在session中获取当前用户名
  32. // 1、登陆页面、初始化页面不过滤
  33. if(loginUrl.equals(path) || initUrl.equals(path)) {
  34. chain.doFilter(req, res);
  35. return;
  36. }
  37. //
  38. if(userName==null){
  39. httpRes.sendRedirect(loginUrl);
  40. return;
  41. }else{
  42. chain.doFilter(req, res);
  43. return;
  44. }
  45. }
  46. @Override
  47. public void init(FilterConfig arg0) throws ServletException {
  48. // TODO Auto-generated method stub
  49. }
  50. }

web.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <!-- configure loginFilter -->
  4. <filter>
  5. <filter-name>loginFilter</filter-name>
  6. <filter-class>com.sale.filter.LoginFilter</filter-class>
  7. </filter>
  8. <filter-mapping>
  9. <filter-name>loginFilter</filter-name>
  10. <url-pattern>*.action</url-pattern>
  11. </filter-mapping>
  12. <!-- configure session timeout 30 minute -->
  13. <session-config>
  14. <session-timeout>30</session-timeout>
  15. </session-config>
  16. </web-app>

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号