1、在web.xml加入过滤器代码
<filter>
<filter-name>requestFilter</filter-name><!-- 过滤器servlet名称-->
<filter-class>itpub.frame.session.RequestFilter</filter-class><!-- 过滤器servlet所在包位置-->
</filter>
<filter-mapping>
<filter-name>requestFilter</filter-name>
<url-pattern>*.do</url-pattern><!-- 过滤器的过滤地址-->
</filter-mapping>
2、创建servlet过滤器
package itpub.frame.session;
import java.io.IOException;
import java.io.PrintWriter;
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;
public class RequestFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpReq = (HttpServletRequest)req;
HttpServletResponse httpRes = (HttpServletResponse)res;
HttpSession httpSession=httpReq.getSession();
if (!httpReq.getServletPath().equals("/logon.do")) {//判断登陆页
if(httpSession.getAttribute("ADMIN_BACKPLAT")==null){
//httpRes.sendRedirect("admin_login.jsp");
httpSession.invalidate();
httpRes.setContentType("text/html;charset=utf-8");
PrintWriter out = httpRes.getWriter();
out.println("<script language='javascript' type='text/javascript'>");
out.println("alert('由于您长时间没有操作导致用户登录信息失效,请您重新登录');window.parent.location.href='" + httpReq.getContextPath() + "/admin_login.jsp'");
out.println("</script>");
}else{
chain.doFilter(req, res);
}
}else{
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}