SpringBoot自定义拦截器Interceptor

发布时间:2024年01月09日


前言

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/**"); // 不需要拦截的请求
    }
}
文章来源:https://blog.csdn.net/qq_40213825/article/details/135363171
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。