Filter实现
定义
过滤器是一个对象,它对资源(servlet 或静态内容)的请求或来自资源的响应执行过滤任务。
过滤器在doFilter方法中执行过滤。 每个过滤器都可以访问一个 FilterConfig 对象,它可以从中获取其初始化参数,
一个对 ServletContext 的引用,它可以使用它来加载过滤任务所需的资源
注册过滤器
1、使用 @Configuration 注解添加到过滤器链中,此方式适用于使用第三方的过滤器。将过滤器写到 FilterConfig 类中,如下:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterLoginBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
String excludeUrl = ".html,.js";
registrationBean.setFilter(new LoginFilter());
//设置过滤器拦截请求
List<String> urls = new ArrayList<>();
//需要拦截的请求路径
registrationBean.addUrlPatterns("/*");
//注册拦截器名称,不定义则为Bean对象name
registrationBean.setName("loginFilter");
//此次可以初始化数据传递给其他的filter
registrationBean.addInitParameter("excludeUrl",excludeUrl);
//优先级
registrationBean.setOrder(1);
return registrationBean;
}
//可以定义多个bean
}
2、@Component注解注册filter
@Component
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
//获取FilterConfig传递的数据
String excludedUrls = filterConfig.getInitParameter("excludeUrl");
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//获取url,包括服务器、端口、服务器路径和协议,不包含参数
StringBuffer url = request.getRequestURL();
//返回服务器路径
String servletPath = request.getServletPath();
}
}
3、使用@WebFilter
@WebFilter(urlPatterns = "/*",filterName = "XssFilter")
public class XssFilter implements Filter {
static Logger log = LoggerFactory.getLogger(XssFilter.class);
private List<String> urlExclusion = new LinkedList<>();
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
{
}
@Override
public void destroy()
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
}