A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 王震阳 于 2014-5-13 21:59 编辑

通常情况下,java web项目都是通过过滤器来判断session是否失效。下面做了一个例子,实现过滤器验证用户的会话是否丢失。
web.xml中的配置:
  1. <filter>  
  2.         <filter-name>filter</filter-name>  
  3.         <filter-class>com.zyujie
  4. .common.LoginFilter</filter-class>  
  5.     </filter>  
  6.     <!-- servlet规范,不能以/*.jsp这样的结尾,写全,或者写成/app/*,这样的才行 -->  
  7.     <filter-mapping>  
  8.         <filter-name>filter</filter-name>  
  9.         <url-pattern>/*</url-pattern>  
  10.     </filter-mapping>  
  11.       
  12.     <session-config>   
  13.         <session-timeout>1</session-timeout>  
  14.     </session-config>  
复制代码

过滤器类:
  1. package com.itheima.common;

  2. import java.io.IOException;
  3. import java.io.PrintWriter;

  4. import javax.servlet.Filter;
  5. import javax.servlet.FilterChain;
  6. import javax.servlet.FilterConfig;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.ServletRequest;
  9. import javax.servlet.ServletResponse;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.servlet.http.HttpSession;

  13. public class LoginFilter implements Filter {

  14. public void destroy() {
  15. // TODO Auto-generated method stub

  16. }

  17. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  18. // TODO Auto-generated method stub
  19. HttpServletRequest request = (HttpServletRequest) req;
  20. HttpServletResponse response = (HttpServletResponse) res;
  21. HttpSession session = request.getSession();
  22. // 如果session不为空,则可以浏览其他页面
  23. String url = request.getServletPath();
  24. System.out.println(url);
  25. //这里判断目录,后缀名,当然也可以写在web.xml中,用url-pattern进行拦截映射
  26. if ((!request.getServletPath().equals("/login.action"))
  27. && (!request.getServletPath().equals("/login.jsp"))
  28. && (!request.getServletPath().equals("/relogin.jsp"))
  29. && (!request.getServletPath().equals("/jquery-1.8.0.min.js"))) {
  30. System.out.println(request.getServletPath());
  31. if (session.getAttribute("userInfo") == null) {
  32. session.invalidate();
  33. response.setContentType("text/html;charset=gb2312");
  34. PrintWriter out = response.getWriter();
  35. out.println("<script language='javascript' type='text/javascript'>");
  36. out.println("alert('由于你长时间没有操作,导致Session失效!请你重新登录!');window.location.href='" + request.getContextPath() + "/relogin.jsp'");
  37. out.println("</script>");
  38. } else {
  39. chain.doFilter(request, response);
  40. }
  41. } else {
  42. chain.doFilter(request, response);
  43. }

  44. }

  45. public void init(FilterConfig arg0) throws ServletException {
  46. // TODO Auto-generated method stub

  47. }

  48. }
复制代码
【阳哥专栏】点点滴滴记录最真实的黑马
http://bbs.itheima.com/thread-117773-1-1.html
(出处: 黑马程序员IT技术论坛)

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马