springboot2.x | 过滤器(Filter)的使用

servlet简介

过滤器,依靠servlet技术。
Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
servlet文档:
https://www.runoob.com/servlet/servlet-intro.html

servlet 和tomcat 是什么关系?

过滤器简介

过滤器Filter,是Servlet的的一个实用技术了。可通过过滤器,对请求进行拦截,比如读取session判断用户是否登录、判断访问的请求URL是否有访问权限(黑白名单)等。主要还是可对请求进行预处理

1.过滤器和拦截器触发时机不一样,过滤器是在请求进入容器后,但请求进入servlet之前进行预处理的。请求结束返回也是,是在servlet处理完后,返回给前端之前。


flq.png

2.拦截器可以获取IOC容器中的各个bean,而过滤器就不行,因为拦截器是spring提供并管理的,spring的功能可以被拦截器使用,在拦截器里注入一个service,可以调用业务逻辑。而过滤器是JavaEE标准,只需依赖servlet api ,不需要依赖spring。


gg.png

1 通过@WebFilter来定义filter,

自定义 AllUrlFilter

@Slf4j
@WebFilter(filterName = "allurlfilter", urlPatterns = {"/*"})
public class AllUrlFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        log.info("all url filter -->" + filterConfig.toString());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("all url filter do filter");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println(request.getHeader("token"));
        //往下文传递
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("all url filter do destroy");
    }
}

在springboot 启动器类上加上注解 @ServletComponentScan

@SpringBootApplication
@ServletComponentScan
public class StudySpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudySpringbootApplication.class, args);
    }
}

总结:
Filter使用白名单过滤Url的方式,配置需要拦截的Url,如果想设置不过滤某些Url需要在doFilter方法中指定。
通过@WebFilter的方式定义Filter,默认使用Filter的类名设置优先级。使用FilterRegistrationBean可以指定优先级

2 filter 中的异常处理

2.1 制造错误

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("all url filter do filter");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        System.out.println(request.getHeader("token"));

        try {
            int i = 0 / 0;
        } catch (Exception e) {
            //错误封装在 request 中
            request.setAttribute("errormsg", e.getMessage());
            //
            request.getRequestDispatcher("/500").forward(request, response);
        }

        filterChain.doFilter(request, response);
    }

尽量使用request.getRequestDispatcher("/500").forward(req, resp);此方式只会在服务器内部转发客户端地址不会发生任何改变;如果使用response.sendRedirect("/500");请求转发,客户端地址会发生改变

2.2 添加/500 url

  @GetMapping("/500")
    public Response excep401(HttpServletRequest request) throws CustomException {

        System.out.println(request.getAttribute("errormsg"));

        throw new CustomException();
    }

方法2 : 通过FilterRegistrationBean来定义 多个filter

所有的filter 去掉 @WebFilter

3.1 新建HelloFilter

@Slf4j
//@WebFilter(filterName = "helloFilter" , urlPatterns = {"/hello/*"})
public class HelloFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        log.info("hello filter --> " + filterConfig.toString());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("hello do filter");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

        log.info("hello do destroy");
    }
}

3.2 新建UserFilter

@Slf4j
//@WebFilter(filterName = "userFilter", urlPatterns = {"/user/*"})
public class UserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        log.info("user filter --> " + filterConfig.toString());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("user do filter");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

        log.info("user do destroy");

    }
}

3.3 新建 FilterConfig 配置

@Configuration
public class FilterConfig {

    @Bean
    public AllUrlFilter allUrlFilter(){
        return new AllUrlFilter();
    }

    @Bean
    public UserFilter userFilter(){
        return new UserFilter();
    }

    @Bean
    public HelloFilter helloFilter(){
        return new HelloFilter();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean(AllUrlFilter allUrlFilter){
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setFilter(allUrlFilter);
        registration.setName("allUrlFilter");
        List urlList  =  new ArrayList<>();
        urlList.add("/*");
        registration.setUrlPatterns(urlList);
        registration.setOrder(1);

        return registration;
    }


    @Bean
    public FilterRegistrationBean filterRegistrationBea2(HelloFilter helloFilter){
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setFilter(helloFilter);
        registration.setName("helloFilter");
        List urlList  =  new ArrayList<>();
        urlList.add("/hello/*");
        registration.setUrlPatterns(urlList);
        registration.setOrder(2);

        return registration;
    }


    @Bean
    public FilterRegistrationBean filterRegistrationBea3(UserFilter userFilter){
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setFilter(userFilter);
        registration.setName("userFilter");
        List urlList  =  new ArrayList<>();
        urlList.add("/user/*");
        registration.setUrlPatterns(urlList);
        registration.setOrder(3);

        return registration;
    }

}

SpringBoot中使用Filter和Interceptor
https://juejin.cn/post/6844903869927931918
Spring Interceptor vs Filter
https://juejin.cn/post/6844903828970553358
SpringBoot图文教程6—SpringBoot中过滤器的使用
https://juejin.cn/post/6844904072173060109

你可能感兴趣的:(springboot2.x | 过滤器(Filter)的使用)