SpringBoot如何实现过滤器,拦截器,添加Servlet ---前提条件,不能去除SpringBoot整合的SpringMVC功能

0.新建一个配置类

package com.roger.springboot;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {


}

注意:Spring5.0之后,必须依赖jdk1.8,接口可以使用default方法,因此WebMvcConfigurerAdapter在Spring5.0之后就

废弃掉了,新建的配置类直接实现WebMvcConfigurer类即可,

如果时Spring5.0之前,则需要继承WebMvcConfigurerAdapter,来实现下面的功能

添加上面的类是为了实现拦截器功能

1.向容器中添加一个过滤器

       1.1) 自定义一个过滤器

package com.roger.springboot.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import java.io.IOException;

@Slf4j
public class CustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化自定义过滤器 CustomFilter...." );
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始处理自定义过滤器功能 CustomFilter....");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        log.info("销毁自定义过滤器 CustomFilter...." );
    }
}

     1.2) 把自定义的过滤器注入到容器中去即在刚刚新建的配置类 WebConfig 中添加相关代码

package com.roger.springboot.config;

import com.roger.springboot.filter.CustomFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 如果项目中只有一个过滤器,可以使用
     *          注解@WebFilter(加在过滤器类上)
     *              +
 *              注解@ServletComponentScan(加在SpringBoot启动类上) 实现
     * 如果项目中有多个过滤器,只能使用下面的方法实现
     * @return
     */
    @Bean
    public FilterRegistrationBean customFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new CustomFilter());
        //针对那些请求地址
        filterRegistrationBean.addUrlPatterns("/*");
        //过滤器的加载顺序
        filterRegistrationBean.setOrder(0);
        return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean anotherFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        //TODO 这里添加另一个过滤器类
        //filterRegistrationBean.setFilter(new AnotherFilter());

        filterRegistrationBean.addUrlPatterns("/*");
        //过滤器的加载顺序
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }
}

2.向容器中添加拦截器

     2.1) 自定义一个拦截器

package com.roger.springboot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {
    /**
     *
     * @return true 进入正式方法 false 该请求直接结束
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("在请求处理之前进行调用(Controller方法调用之前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
    }
}

    2.2) 重写新建的配置类继承WebMvcConfigurer类的addInterceptors(InterceptorRegistry registry) 方法

package com.roger.springboot.config;

import com.roger.springboot.filter.CustomFilter;
import com.roger.springboot.interceptor.CustomInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
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;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired(required = false)
    private CustomInterceptor customInterceptor;

    /**
     * 如果项目中只有一个过滤器,可以使用
     *          注解@WebFilter(加在过滤器类上)
     *              +
 *              注解@ServletComponentScan(加在SpringBoot启动类上) 实现
     * 如果项目中有多个过滤器,只能使用下面的方法实现
     * @return
     */
    @Bean
    public FilterRegistrationBean customFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new CustomFilter());
        //针对那些请求地址
        filterRegistrationBean.addUrlPatterns("/*");
        //过滤器的加载顺序
        filterRegistrationBean.setOrder(0);
        return filterRegistrationBean;
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(customInterceptor)
            .addPathPatterns("/**")//进行拦截的url地址集合或者正则表达式
            .excludePathPatterns("/index.html");//不进行拦截的url地址集合或者正则表达式
        //如果还有其他拦截器,继续添加
    }
}

    2.3) 验证效果:

        发送请求:

            

   后台打印日志

 

猜你喜欢

转载自blog.csdn.net/lihongtai/article/details/89452185