自定义Filter过滤静态资源

在springMVC中,可以通过配置来过滤静态资源,

也可以在web.xml中进行配置,通过自定义Filter来实现。

web.xml配置如下。

	<filter>
		<filter-name>securityFilter</filter-name>
		<filter-class>com.wswhr.SecurityFilter</filter-class>
		<init-param>
			<param-name>ignores</param-name>
			<param-value>/perm/getCanalChargeUsers,/changePW,/app/appNavs,/app/download,/tulogin,/tulogout,/static,/login,/img/select,/tokenMethod,/deleteToken</param-value>
		</init-param>
	</filter>
<span style="white-space:pre">	</span><filter-mapping>
<span style="white-space:pre">		</span><filter-name>securityFilter</filter-name>
<span style="white-space:pre">		</span><url-pattern>*</url-pattern>
<span style="white-space:pre">	</span></filter-mapping>

Filter中,有个init方法,会在web容器创建Filter的时候调用,因此,可以利用这个方法来传一些参数。

参考文章:http://www.cnblogs.com/hellojava/archive/2012/12/19/2824444.html

用户在配置filter时,可以使用<init-param>为filter配置一些初始化参数,当web容器实例化Filter对象,调用其init方法时,会把封装了filter初始化参数的filterConfig对象传递进来。

Filter代码如下:

package com;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

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;

public class SecurityFilter implements Filter {

	private Set<String> prefixIignores = new HashSet<String>();
	
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		if (canIgnore(request)) {
			chain.doFilter(req, res);
			return;
		}
		
		try {
			chain.doFilter(request, response);//已经登录
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	public void init(FilterConfig config) throws ServletException {

		String cp = config.getServletContext().getContextPath();
		String ignoresParam = config.getInitParameter("ignores");
		String[] ignoreArray = ignoresParam.split(",");
		for (String s : ignoreArray) {
			prefixIignores.add(cp + s);
		}
	}

	@Override
	public void destroy() {
		prefixIignores = null;
	}

	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getRequestURI();
		for (String ignore : prefixIignores) {
			if (url.startsWith(ignore)) {
				return true;
			}
		}
		return false;
	}
	
}


相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页