欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot使用Interceptor(拦截器)的集成配置

程序员文章站 2022-04-19 21:33:03
...

第一步

增加Interceptor类,实现HandlerInterceptor接口。

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author :Mall
 * @date :Created in 2021-02-26
 * @description :
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

    /**
     * 这个方法是在访问接口之前执行的
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        return true;
    }
}

第二步

增加WebConfiguration,实现【WebMvcConfigurer】或【WebMvcConfigurationSupport】接口

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @version: v1.0
 **/
@Configuration
public class BaseConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private RequestInterceptor requestInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        String[] filterPath = {
          "要拦截的地址"
        };

        registry.addInterceptor(requestInterceptor).addPathPatterns(filterPath);
    }

}

注:此处需要注意,如果配置类是实现的WebMvcConfigurer类,要查一下代码中是否有WebMvcConfigurationSupport类,因为优先要使用WebMvcConfigurationSupport,否则addInterceptor无法加载。

相关标签: spring boot