SpringBoot过滤器与拦截器(7)

一、过滤器Filter

 创建过滤器的方法很简单,也传统的WEB项目一样,实现 Filter接口即可

package com.hanzhenya.learnspringboot.filter;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
public class MyFilter implements Filter {
 
    private static final Logger LOGGER=LoggerFactory.getLogger(MyFilter.class);
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
 
        LOGGER.info("自定义过滤器工作,当前请求URL:{}", httpServletRequest.getRequestURL());
        LOGGER.info("自定义过滤器工作,当前请求URI:{}", httpServletRequest.getRequestURI());
 
        //放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

  

在SpringBoot中的步骤

        (1)实现 Filter 接口,实现其中的 doFilter() 方法;

        (2)添加 @Configuration 注解,将自定义 Filter 加入过滤链。

          SpringBoot的优势几乎就在于,所有的配置均有Java来控制。比如添加匹配过滤,addUrlPattern。

          order是拦截顺序,数值越小,拦截优先级越高。

package com.hanzhenya.learnspringboot.config;
 
import com.zhoutianyu.learnspringboot.filter.MyFilter;
import com.zhoutianyu.learnspringboot.filter.MyFilter2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class FilterConfig {
 
    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean<MyFilter> filterContainer = new FilterRegistrationBean<>();
        filterContainer.setFilter(new MyFilter());
        //filter pattern
        filterContainer.addUrlPatterns("/*");
        //filter name
        filterContainer.setName("MyFilter");
        //filter order
        filterContainer.setOrder(1);
        return filterContainer;
    }
 
}

二、拦截器Interceptor

过滤器与拦截器,这两个词汇其实本质上是一样的。都是对URL进行处理与拦截。

        Filter侧重点是要不要让某个请求进入我们系统。

        Interceptor侧重点是请求进入我们的系统后,进行预处理、后处理。

        编写拦截器最常见也是最简单的方法是,继承HandlerInterceptorAdapter。
 (1)编写一个拦截器并声明为一个Bean

package com.hanzhenya.learnspringboot.interceptor;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class);
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("资源预处理");
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        LOGGER.info("资源后处理");
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        LOGGER.info("请求完成,清理资源");
    }
 
}

(2)将拦截器添加到WEB配置中。

package com.hanzhenya.learnspringboot.config;
 
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zhoutianyu.learnspringboot.interceptor.MyInterceptor;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
import javax.annotation.Resource;
 
@Configuration
public class CustomWebConfigure implements WebMvcConfigurer {
 
    @Resource
    private MyInterceptor interceptor;
 
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).addPathPatterns("/**")
               .excludePathPatterns("/static/**");
    }
}

  

posted @ 2021-03-31 15:22  hzy_叶子  阅读(68)  评论(0编辑  收藏  举报