Spring MVC 拦截器编程开以及常见问题

写在前面:最近在对一个微服务增减接口拦截器的时候,定义的拦截器未能生效,并且未报任何异常,swagger的ui也无法正常访问。经查明原因:prehandler方法最后返回的布尔值是false,拦截器定义部分是从其他服务拷贝的文件,由于没有检查,导致未能生效。

  1. 配置拦截器

我这里配置拦截器没有使用 xml,使用的是java的方式配置的interceptor,这样比较直观,更容易理解。

InterceptorConfig这个类继承WebMvcConfigurerAdapter 抽象类,WebMvcConfigurerAdapter 抽象类 实现了 WebMvcConfigurer 接口。WebMvcConfigurer 该接口可以对拦截器的很多属性进行配置。

java 复制代码
package com.example.swaggertest.demos.web.Config;

import com.example.swaggertest.demos.web.Interceptor.CollrollerInterceptorHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //覆写拦截器过滤条件
        registry.addInterceptor(new CollrollerInterceptorHandler())
                .addPathPatterns("/**");  //对所有的接口进行过滤
    }


}
  1. 定义拦截器

CollrollerInterceptorHandler 实现了HandlerInterceptor 接口,这个接口里定义了三个方法,如代码所示。

java 复制代码
package com.example.swaggertest.demos.web.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class CollrollerInterceptorHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //编写拦截业务
        return true; //注意一定要返回true,否则容易出现与swagger集成问题,导致不能访问swagger的ui
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
  1. 拦截器与过滤器的区别

拦截器与过滤器的区别

相关推荐
Cyanto28 分钟前
Spring注解IoC与JUnit整合实战
java·开发语言·spring·mybatis
qq_4338889328 分钟前
Junit多线程的坑
java·spring·junit
gadiaola33 分钟前
【SSM面试篇】Spring、SpringMVC、SpringBoot、Mybatis高频八股汇总
java·spring boot·spring·面试·mybatis
写不出来就跑路35 分钟前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
Cyanto41 分钟前
深入MyBatis:CRUD操作与高级查询实战
java·数据库·mybatis
麦兜*1 小时前
Spring Boot 集成Reactive Web 性能优化全栈技术方案,包含底层原理、压测方法论、参数调优
java·前端·spring boot·spring·spring cloud·性能优化·maven
天上掉下来个程小白1 小时前
MybatisPlus-06.核心功能-自定义SQL
java·spring boot·后端·sql·微服务·mybatisplus
知了一笑1 小时前
独立开发第二周:构建、执行、规划
java·前端·后端
今天背单词了吗9802 小时前
算法学习笔记:17.蒙特卡洛算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·笔记·考研·算法·蒙特卡洛算法
Dcs2 小时前
从 C 到 Rust:一位开发者的 `tmux` 全面移植之旅
java