Filter介绍

Filter是Servlet规范规定的,不属于spring框架,也是用于请求的拦截。但是它适合更粗粒度的拦截,在请求前后做一些编解码处理、日志记录等。

一个Filter包括:
1)、在servlet被调用之前截获;
2)、在servlet被调用之前检查servlet request;
3)、根据需要修改request头和request数据;
4)、根据需要修改response头和response数据;
5)、在servlet被调用之后截获

实现方式

一、基于注解方式

1.编写自己的filter

import java.io.IOException;

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.annotation.WebFilter; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order; /**
* 自定义过滤器
* @ClassName: CustomFilter
* @Description: 过滤器,顾名思义,能够过滤一切请求(而拦截器只能过滤action请求),包括静态资源的请求。
* chain.doFilter(request, response)表示过滤通过,能够往下执行。
* 所以过滤操作要写在chain.doFilter(request, response) 前面,作一些条件判断;
* 如果不符合条件,则不执行chain.doFilter(request, response);
* @author OnlyMate
* @Date 2018年8月28日 下午3:04:44
*
*/
@Order(1)//定义优先级
@WebFilter(filterName="CustomFilter",urlPatterns="/*")
public class CustomFilter implements Filter{
private Logger logger = LoggerFactory.getLogger(CustomFilter.class); @Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("CustomFilter ==> init method: init");
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("CustomFilter ==> doFilter method: before");
chain.doFilter(request, response);//执行请求
logger.info("CustomFilter ==> doFilter method: after");
} @Override
public void destroy() {
logger.info("CustomFilter ==> destroy method: destroy");
} }

2.配置

在项目的启动入口上加上@ServletComponentScan注解,开启扫描所有的servlet组件

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
//使用 @EnableWebMvc 注解,需要以编程的方式指定视图文件相关配置;
//@EnableWebMvc
//使用 @EnableAutoConfiguration 注解,会读取 application.properties 或 application.yml 文件中的配置
@EnableAutoConfiguration
@ServletComponentScan//springboot启动类扫描servlet组件(过滤器)
public class Application {
public static ApplicationContext applicationContext; private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) {
startApplication(args);
} public static ApplicationContext startApplication(String[] args) {
if (applicationContext == null) {
logger.info(" >>> Springboot Application 开始启动...");
SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
SpringApplication application = builder.application();
Set<String> sources = new HashSet<>();
sources.add("classpath:applicationContext.xml");
application.setSources(sources); applicationContext = application.run(args);
logger.info(" >>> Springboot Application 启动完成!");
}
return applicationContext;
} public static ApplicationContext getApplicationContext() {
if (applicationContext == null) {
logger.error(" >>> Error:Springboot Application ApplicationContext is Null.");
}
return applicationContext;
} }

二、基于Java配置

1.编写自己的filter

import java.io.IOException;

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 自定义过滤器
* @ClassName: CustomPlainFilter
* @Description: 过滤器,顾名思义,能够过滤一切请求(而拦截器只能过滤action请求),包括静态资源的请求。
* chain.doFilter(request, response)表示过滤通过,能够往下执行。
* 所以过滤操作要写在chain.doFilter(request, response) 前面,作一些条件判断;
* 如果不符合条件,则不执行chain.doFilter(request, response);
* @author OnlyMate
* @Date 2018年8月28日 下午3:04:44
*
*/
public class CustomPlainFilter implements Filter{
private Logger logger = LoggerFactory.getLogger(CustomPlainFilter.class); @Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("CustomPlainFilter ==> init method: init");
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("CustomPlainFilter ==> doFilter method: before");
chain.doFilter(request, response);//执行请求
logger.info("CustomPlainFilter ==> doFilter method: after");
} @Override
public void destroy() {
logger.info("CustomPlainFilter ==> destroy method: destroy");
} }

2.配置

自定义一个配置类

这里的配置有两种方式,第一种是通过动态代理去找"customPlainFilter"对应的实体bean,第二种方式是直接注入自定义的filter(CustomFilterConfigurer)

/**
* 自定义一个配置类
* @ClassName: CustomFilterConfigurer
* @Description: TODO
* @author OnlyMate
* @Date 2018年8月31日 下午3:25:51
*
*/
@Configuration
public class CustomFilterConfigurer {
@Bean
public FilterRegistrationBean<DelegatingFilterProxy> testFilterRegistration() { FilterRegistrationBean<DelegatingFilterProxy> registration = new FilterRegistrationBean<DelegatingFilterProxy>();
//第一种方式,使用动态代理的方式
registration.setFilter(new DelegatingFilterProxy("customPlainFilter"));
//第二种方式,直接注入一个filter
// registration.setFilter(new CustomPlainFilter());
// registration.setName("customPlainFilter");
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setEnabled(true);
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setOrder(1);
return registration;
} @Bean(name="customPlainFilter")
public CustomPlainFilter createCustomPlainFilter() {
return new CustomPlainFilter();
}
}

效果图

Spring Boot实践——Filter实现-LMLPHP

总结

Spring Boot实现一个过滤器与传统的方式差别很大,有想了解的可以看之前转载别人的一篇

Spring boot下添加filter

05-08 08:22