一、编写Filter拦截器类
1 package com.pv.utils; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.*; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.HttpSession; 10 11 public class RequestFilter implements Filter { 12 private FilterConfig config; 13 //实现初始化方法 14 public void init(FilterConfig config){ 15 this.config = config; 16 } 17 public void destroy(){ 18 this.config = null; 19 } 20 21 @Override 22 public void doFilter(ServletRequest req, ServletResponse res, 23 FilterChain chain) throws IOException, ServletException { 24 // TODO Auto-generated method stub 25 req.setCharacterEncoding("utf-8"); 26 HttpServletRequest request = (HttpServletRequest) req; 27 HttpServletResponse response = (HttpServletResponse) res; 28 HttpSession session = request.getSession(); 29 //获取客户请求的页面 30 String url = request.getServletPath(); 31 System.out.println("wangming"+url); 32 if((!request.getServletPath().equals("/login.jsp")) 33 &&(!request.getServletPath().equals("/solar.jsp")) 34 &&(!request.getServletPath().equals("/index.jsp"))){ 35 System.out.println(request.getServletPath()); 36 if(session.getAttribute("username")==null){ 37 session.invalidate(); 38 response.setContentType("text/html;charset=gb2312"); 39 PrintWriter out = response.getWriter(); 40 out.println("<script language=‘javascript‘ type=‘text/javascript‘>"); 41 out.println("alert(‘由于你长时间没有操作,导致Session失效!请你重新登录!‘);top.location.href=‘" + request.getContextPath() + "/solar.jsp‘"); 42 out.println("</script>"); 43 }else{ 44 chain.doFilter(request , response ); 45 } 46 }else{ 47 chain.doFilter(request , response ); 48 } 49 } 50 }
二、在web.xml中配置拦截器
1 <session-config> 2 <session-timeout>1</session-timeout> 3 </session-config> 4 5 <filter> 6 <filter-name>RequestFilter</filter-name> 7 <filter-class>com.pv.utils.RequestFilter</filter-class> 8 </filter> 9 <filter-mapping> 10 <filter-name>RequestFilter</filter-name> 11 <url-pattern>*.jsp</url-pattern> 12 </filter-mapping>
时间: 2024-10-11 22:34:54