首页 > 代码库 > javaweb之session过期验证

javaweb之session过期验证

session过期判断的基本思想:用户登录成功后,将用户账号信息保存在session中,然后几乎每次执行命令都要经过过滤器,过滤器检查session中是否存在账号,若不存在,

则返回登录页面,反之正常执行。

1、web.xml中添加

<filter><!-- 配置过滤器,用来检查session中是否存在用户登录账号信息 -->    <filter-name>ChkSessionFilter</filter-name>    <filter-class>com.um.core.filter.LoginFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>ChkSessionFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>
<!-- 配置session过期时间 -->
<session-config><session-timeout>20</session-timeout></session-config><welcome-file-list>

 

 

2、fiter

 package com.um.core.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import com.um.core.controller.BaseController;/** * 登录验证过滤器 */public class LoginFilter extends BaseController implements Filter {    /**     * 初始化     */    public void init(FilterConfig fc) throws ServletException {        // FileUtil.createDir("d:/FH/topic/");    }    public void destroy() {    }    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)            throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) res;        String[] notFilter = new String[] { "userLogin","js","xml","css","demo","img","images","fonts","common","gateway","payCallback","toOrderPage","show_order"};//过滤字段、路径。。。。。。        String urlPath = request.getServletPath();        Boolean flg = false;        for (String url : notFilter) {            if ((urlPath.contains(url))) {                flg = true;            }        }        if(flg){            chain.doFilter(req, res);        }else{            HttpSession session = request.getSession();            String UID = (String) session.getAttribute("UID"); //登录成功将登录ID放入session中,这里将session取出对比            if (null == UID||"".equals(UID)) {                logger.warn("用户登录超时或未登录,请重新登录!");                java.io.PrintWriter out = response.getWriter();                  out.println("<html>");                  out.println("<script>");                  out.println("window.open (‘"+request.getContextPath()+"/login.jsp‘,‘_top‘)");                  out.println("</script>");                  out.println("</html>");                  return;                            }else {                chain.doFilter(req, res);            }        }            }}

 

javaweb之session过期验证