首页 » 互联网资讯 » java » 正文

javaweb中用Filter过滤失效的Session

  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.     <session-config>
  12.         <session-timeout>1</session-timeout>
  13.     </session-config>                                        ~~~

通常情况下,java web项目都是通过过滤器来判断session是否失效。下面做了一个例子,实现过滤器验证用户的会话是否丢失。
web.xml中的配置:

···········

  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. 过滤器类:

发表评论