session失效后跳转到登陆页面

一、编写Filter拦截器类 

 package com.pv.utils;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class RequestFilter implements Filter {
private FilterConfig config;
//实现初始化方法
public void init(FilterConfig config){
this.config = config;
}
public void destroy(){
this.config = null;
} @Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
req.setCharacterEncoding("utf-8");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
//获取客户请求的页面
String url = request.getServletPath();
System.out.println("wangming"+url);
if((!request.getServletPath().equals("/login.jsp"))
&&(!request.getServletPath().equals("/solar.jsp"))
&&(!request.getServletPath().equals("/index.jsp"))){
System.out.println(request.getServletPath());
if(session.getAttribute("username")==null){
session.invalidate();
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<script language='javascript' type='text/javascript'>");
out.println("alert('由于你长时间没有操作,导致Session失效!请你重新登录!');top.location.href='" + request.getContextPath() + "/solar.jsp'");
out.println("</script>");
}else{
chain.doFilter(request , response );
}
}else{
chain.doFilter(request , response );
}
}
}

二、在web.xml中配置拦截器  

 <session-config>
<session-timeout>1</session-timeout>
</session-config> <filter>
<filter-name>RequestFilter</filter-name>
<filter-class>com.pv.utils.RequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
上一篇:Linux mint 18版本开启SSH服务


下一篇:MySQL安装教程并使用springboot2和Mybatis测试