spring boot 使用拦截器
1.创建拦截器类,继承HandlerInterceptor
2.注册拦截器,指定拦截规则

spring framework 中的拦截器类需要继承与HandlerInterceptor,spring boot也是一致的

package com.tons.intercept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class RecordIntercept implements HandlerInterceptor {
    /*
      request 请求对象
      response 响应对象
      handler 请求处理器,可以强转成HandlerMethod使用(可获取处理方法的相关信息)。
    */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取路由
        String remoteAddr = request.getRemoteAddr();
        // 获取访问路径 http:localhost:80/ 后面的url部分
        String url = request.getRequestURI();
        // 打印
        log.debug("{}访问了[{}]",remoteAddr,url);
        // 返回true 放行,false不放行
        return true;
    }
}

注册拦截器,指定拦截规则

package com.tons.config;
import com.tons.intercept.PowerIntercept;
import com.tons.intercept.RecordIntercept;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.List;
/**
 * 配置拦截器
 */
@Configuration
public class InterceptConfig implements WebMvcConfigurer {
    private static final List<String> STATIC_PATH = Arrays.asList("/","/index","/css/**","/js/**","/img/**","/media/**","/vendors/**","/element-ui/**","/temp/**","/public/**","/json/**","/favicon.ico","/error");
    /**
     * 配置拦截器
     * @param registry 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        //addPathPatterns 拦截路径
        //excludePathPatterns 不拦截路径
        // /**代表当前目录下所有资源(包含其内部子资源)
        registry.addInterceptor(new RecordIntercept()).addPathPatterns("/**").excludePathPatterns(STATIC_PATH);
    }
}

发表回复