SpringBoot自定义拦截器Interceptor

文章目录

  • 前言
  • 示例
    • 1. 自定义拦截器
    • 2. 配置类


前言

SpringBoot 自定义一个拦截器

示例

1. 自定义拦截器

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;

@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 执行Controller方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("MyInterceptor 执行 preHandle, request uri={}, url={}", request.getRequestURI(), request.getRequestURL());
        return true; // 返回false,请求将被拦截,返回true代表放行
    }

    /**
     * 执行Controller方法之后,响应给前端之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("MyInterceptor 执行 postHandle");
    }

    /**
     * 响应给前端之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("MyInterceptor 执行 afterCompletion");
    }
}

2. 配置类

import com.idiudiu.api.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
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 WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor) // 注册自定义拦截器
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns("/api/msg/**"); // 不需要拦截的请求
    }
}

你可能感兴趣的:(网络编程,spring,boot,后端,java)