/**
* cn.jbit.filter3.CheckLoginFilter
* 用户登录过滤器
* 配置参数
* checkSessionKey 需检查在Session中保存的关键字
* redirectURL 重定向页面,URL不包括ContextPath
* notCheckURLList 不做检查的URL列表,以分号分开,URL不包括ContextPath
* 2014-2-18
*/
package cn.jbit.filter;
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 javax.servlet.http.HttpSession;
public class CheckLoginFilter implements Filter {
private FilterConfig config;
private String redirectURL;// 重定向页面
private List<String> notCheckURLList = new ArrayList<String>();// 不做检查的URL列表
private String sessionKey;// Session中保存的关键字
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession();
if (null == sessionKey || "".equals(sessionKey)) {
chain.doFilter(request, response);
return;
}
boolean result = checkRequestURLNotFilterList(request);
if (!result && session.getAttribute(sessionKey) == null) {
response.sendRedirect(request.getContextPath() + redirectURL);
return;
}
chain.doFilter(request, response);
}
/**
* 请求是否过滤
*
* @param request 请求
* @return true不过滤,false过滤
*/
public boolean checkRequestURLNotFilterList(HttpServletRequest request) {
String uri = request.getServletPath()
+ (request.getPathInfo() == null ? "" : request.getPathInfo());
return notCheckURLList.contains(uri);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
redirectURL = config.getInitParameter("redirectURL");
sessionKey = config.getInitParameter("checkSessionKey");
String notCheckURLStr = config.getInitParameter("notCheckURLList");
if (null != notCheckURLStr) {
String[] splitStr = notCheckURLStr.split(";");
notCheckURLList.clear();// 清空集合
for (String str : splitStr) {
notCheckURLList.add(str);
}
}
}
public void destroy() {
notCheckURLList.clear();
config = null;
redirectURL = null;
sessionKey = null;
}
}
用户登录过滤器
最新推荐文章于 2022-09-13 09:19:35 发布