1. 程式人生 > >配置過濾器對某個路徑下的資源不進行攔截

配置過濾器對某個路徑下的資源不進行攔截

public class LoginFilter implements Filter{

	private Logger logger = Logger.getLogger(LoginFilter.class);
	private String[] ignoreArr=null;
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ignoreArr=filterConfig.getInitParameter("ignore").split(",");	
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest HttpRequest=(HttpServletRequest)request;
		HttpServletResponse HttpResponse=(HttpServletResponse)response;
		boolean flag=isIgnore(HttpRequest);
		if(flag) {
			chain.doFilter(HttpRequest, HttpResponse);
		}else {
			UserLoginModel wechat= (UserLoginModel) 
                     HttpRequest.getSession().getAttribute("user");
			UserLoginModel admin=(UserLoginModel)                     
                     HttpRequest.getSession().getAttribute("userInfo");
			if(wechat!=null||admin!=null) {
				chain.doFilter(HttpRequest, HttpResponse);
			}else {
				return ;
			}
		}
	}

	@Override
	public void destroy() {
		
	}
	
	
	public boolean isIgnore(HttpServletRequest request) {
		String path=request.getRequestURI().toLowerCase();
		for(String ignore:ignoreArr) {
			if(path.contains(ignore)) {
				return true;
			}
		}
		return false;
	}
}

web.xml配置

<filter>
   <filter-name>LoginFilter</filter-name>
   <filter-class>com.shineiot.wechatapp.filter.LoginFilter</filter-class>
   <init-param>
        <param-name>ignore</param-name>
    	<param-value>
            /resources/,/userlogin/login,/userlogin/adminlogin.htm,/userlogin/register,/wechatapp/</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LoginFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>