校验用户是否登录过滤器Filter

1、首先需要在web.xml中配置过滤器

 

<!-- servlet 校验是否登录过滤器 -->
   <filter>
	  <filter-name>CheckLoginFilter</filter-name>
	  <filter-class>net.cnki.tpi.cms.util.CheckLoginFilter</filter-class>
	  <init-param>
	  <param-name>redirectURL</param-name>
	  <param-value>/login.jsp</param-value>
	  </init-param>
	  <init-param> 
	       <param-name>notCheckURLList </param-name> 
	       <param-value>/error.jsp;/login.jsp</param-value> 
	  </init-param> 
   </filter>
   <filter-mapping>
	  <filter-name>CheckLoginFilter</filter-name>
	  <url-pattern>/*</url-pattern>
   </filter-mapping>

 2、然后新创建一个CheckLoginFilter.java类,代码如下:

 

	/**
 *  校验用户是否已登录过滤器
 * @author lpz
 *
 */
public class CheckLoginFilter implements Filter {
	
	private FilterConfig filterConfig = null;         
     private String redirectURL = null;         
     private List notCheckURLList = new ArrayList();    

    public CheckLoginFilter() {
    }

	public void destroy() {
		notCheckURLList.clear();
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		HttpSession session = request.getSession();
		Object userInfo = session.getAttribute("userInfo");
		if(!checkRequestURIIntNotFilterList(request) && userInfo==null){
			 //重定向到指定页面
			 response.sendRedirect(request.getContextPath() + redirectURL); 
		}else{
			//继续响应请求
			chain.doFilter(servletRequest, servletResponse);
		}
	}
	
	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig = fConfig;
		redirectURL = filterConfig.getInitParameter("redirectURL");
		String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
		if(!MyStringUtil.isNullOrEmpty(notCheckURLListStr)){
                        //将字符串转化为list
			notCheckURLList = MyStringUtil.convStrToList(notCheckURLListStr,";");
		}
	}
	/**
	 * 校验当前请求是否在不过滤的列表中
	 * @param request
	 * @return
	 */
	private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)         
	{         
	    String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());         
	    return notCheckURLList.contains(uri);         
	}    

}

 

你可能感兴趣的:(filter)