SessionFilter:
package com.duocy.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 com.duocy.bean.Client;
import com.duocy.bean.Emp;
public class SessionFilter implements Filter {
//需要定义系统页面访问中可放行的连接
private List<String> list = new ArrayList<String>();
public void init(FilterConfig arg0) throws ServletException {
//定义前台不被拦截的页面
list.add("/index.html");
list.add("/login.html");
list.add("/register.jsp");
list.add("/customer-case.html");
list.add("/product-show.html");
list.add("/solutions.html");
list.add("/getFindkey.jsp");
//定义管理后台不被拦截的页面
list.add("/admin/login.html");
list.add("/admin/assets");
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//1、获取页面中的访问的路径连接
String path = request.getServletPath();
if(list!=null && list.contains(path)){
//如果页面中获取的访问连接于定义的可放行的连接一致,则放行
chain.doFilter(request, response);
return;
}
//2、从session(globle_user)对象中获取当前登录的用户
Client client = (Client) request.getSession().getAttribute("LoginClient");
Emp emp = (Emp) request.getSession().getAttribute("LoginEmp");
if(client!=null){
//如果从session中获取的用户对象不为空,则放行
chain.doFilter(request, response);
return;
}else{
//如果不满足条件1和2,则不能放行,回到客户登录页面
response.sendRedirect(request.getContextPath()+"/login.html");
return;
}
/*if(emp!=null) {
//如果从session中获取的用户对象不为空,则放行
chain.doFilter(request, response);
return;
}else {
//如果不满足条件1和2,则不能放行,回到管理登录页面
response.sendRedirect(request.getContextPath()+"/EmpCheackLogin");
return;
}*/
}
public void destroy() {
}
}
web.xml配置:
<!-- 过滤所有对jsp的请求-->
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.duocy.util.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!-- Session过期 -->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
个人记录之用!