springboot 过滤器实现的具体步骤

过滤器,顾名思义,能够过滤一切请求(而拦截器只能过滤action请求),包括静态资源的请求。

实现很简单:

(1)写一个过滤器。过滤实现在doFilter方法里面。chain.doFilter(request, response)  表示过滤通过,能够往下执行。所以过滤操作要写在chain.doFilter(request, response) 前面,作一些条件判断,如果不符合条件,则不执行chain.doFilter(request, response);

@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("MyFilter init............");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("MyFilter doFilter.........before");
        chain.doFilter(request, response);
        System.out.println("MyFilter doFilter.........after");
    }
    @Override
    public void destroy() {
        System.out.println("MyFilter destroy..........");
    }
}
(2)别忘了让springboot启动类扫描servlet组件,否则是不生效的,扫描的注解是@ServletComponentScan。
@SpringBootApplication
@ServletComponentScan
public class SpringbootCompanyApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringbootCompanyApplication.class, args);
	}
}
完成。

你可能感兴趣的:(java,后端,spring)