用户登录过滤器

/**
 * 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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值