【SpringMVC配置失效】Springboot2.x拦截器配置不无生效
一.环境
maven springboot版本2.x
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
二.无效的拦截器代码
自定义拦截器
/**
* @author: Gabriel
* @date: 2020/2/5 13:45
* @description 登录认证拦截
*/
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor { @Autowired
IUserService userService; /**
* 前置处理-方法执行前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
//如果不是映射到方法就放行
if (!(handler instanceof HandlerMethod)) {
return true;
} HandlerMethod handlerMethod = (HandlerMethod) handler;
//获取方法及其相关注解
//检查是否有不需要登录的注解,有则跳过认证
Method method = handlerMethod.getMethod();
if (method.isAnnotationPresent(NoRequiredLoginToken.class)) {
NoRequiredLoginToken noRequiredLoginToken = method.getAnnotation(NoRequiredLoginToken.class);
if (noRequiredLoginToken.required()) {
return true;
}
} //检查有没有需要用户权限的注解
if (method.isAnnotationPresent(RequiredLoginToken.class)) {
RequiredLoginToken requiredLoginToken = method.getAnnotation(RequiredLoginToken.class);
if (requiredLoginToken.required()) {
//执行认证
if (StringUtils.isBlank(token)) {
throw new BusinessException(ResultCode.NO_LOGIN);
}
//获取token中的userId
String userId;
try {
userId=JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException e) {
throw new BusinessException(ResultCode.NO_LOGIN);
}
User user = userService.getById(userId);
if (ObjectUtil.isNull(user)) {
//TODO 用户不存在,请重新登录,这里需要优化异常类的构造方法
throw new BusinessException(ResultCode.NO_LOGIN);
}
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
//TODO 校验失败,token有误
throw new BusinessException(ResultCode.NO_LOGIN);
}
return true;
}
} //未加注解的方法直接放行-默认是不需要校验的
return true;
} /**
* 后置处理-方法执行后执行
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /**
* 最终处理-控制器执行完成后执行
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}
注册拦截器
/**
* @author: Gabriel
* @date: 2020/2/5 14:15
* @description 登录拦截配置
*/
@Configuration
@Order(1)
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private AuthenticationInterceptor authenticationInterceptor; @Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**");
} }
目的是拦截相关的接口,但是一直没生效,最后发现是有其他的WebMvc相关配置冲突了,有其他的类继承了 WebMvcConfigurationSupport,导致冲突
冲突的代码
**
* @author Gabriel
* @date 2020-01-08
* @description 自定义SpringMvc转换器 解决数据转换问题(例如BigDecimal转换为String,解决精度问题)
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport { /**
* Date格式化字符串
*/
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/**
* DateTime格式化字符串
*/
private static final DateTimeFormatter DATETIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* Time格式化字符串
*/
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss"); @Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = converter.getObjectMapper(); // 反序列化失败
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // long 转换为字符串
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); // 浮点型使用字符串
simpleModule.addSerializer(Double.class, ToStringSerializer.instance);
simpleModule.addSerializer(Double.TYPE, ToStringSerializer.instance);
simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance); // java8 时间格式化
simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATETIME_FORMAT));
simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DATE_FORMAT));
simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(TIME_FORMAT)); objectMapper.registerModule(simpleModule); // 为mapper注册一个带有SerializerModifier的Factory,处理null值
objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
//CustomizeBeanSerializerModifier 自定义序列化修改器
.withSerializerModifier(new CustomizeBeanSerializerModifier())); // 处理中文乱码问题
converter.setSupportedMediaTypes(ImmutableList.of(MediaType.APPLICATION_JSON_UTF8)); converter.setObjectMapper(objectMapper);
converters.add(converter);
converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
}
解决方案:
去掉该配置即可,或者去掉@Configure注解,使该文件不生效
【SpringMVC配置失效】Springboot2.x拦截器配置不无生效的更多相关文章
- springmvc以及springboot中的拦截器配置
拦截器两种实现 如果不同的controller中都需要拦截器,不能使用相同的拦截器,因为拦截器不能跨controller,这个时候只能为不同的controller配置不同的拦截器,每一个拦截器只能 ...
- 拦截器配置类使用继承写法导致jackson的全局配置失效
问题描述 项目中需要一个拦截器用于拦截请求,在没有请求中生成requestId.然后写了一个配置类,这个类继承了 WebMvcConfigurationSupport类,重写了addIntercept ...
- SpringMVC配置多个自定义拦截器
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- SpringBoot2.0 基础案例(05):多个拦截器配置和使用场景
一.拦截器简介 1.拦截器定义 拦截器,请求的接口被访问之前,进行拦截然后在之前或之后加入某些操作.拦截是AOP的一种实现策略. 拦截器主要用来按照指定规则拒绝请求. 2.拦截器中应用 Token令牌 ...
- Spring 拦截器配置
Spring interceptor拦截器配置 Spring mvc的拦截器是通过handlerinterceptor来实现的 实现方式: 1.自定义一个类实现Spring的handlerinterc ...
- Struts2 拦截器配置以及实现
@(Java ThirdParty)[Struts|Interceptor] Struts2 拦截器配置以及实现 Struts2的拦截器应用于Action,可以在执行Action的方法之前,之后或者两 ...
- Struts2学习笔记(拦截器配置添加)
一.拦截器工作原理: 根据Struts2的工作原理图,拦截器在action执行前进行顺序调用,之后执行Action并返回结果字符串,再逆序调用拦截器.(结构类似递归方式...)大部分时候,拦截器方法都 ...
- spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项
原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.o ...
- Struts2拦截器配置
1. 理解拦截器 1.1. 什么是拦截器: 拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作.拦截是AO ...
随机推荐
- react入个门
起步 react 特点 不使用模板 不是一个mvc框架 响应式 轻量级的js库 原理 虚拟dom 将dom抽象成js对象 diff算法 搭建开发环境 react.js 核心文件 react-dom.j ...
- 215. 数组中的第K个最大元素 + 快速排序 + 大根堆
215. 数组中的第K个最大元素 LeetCode-215 另一道类似的第k大元素问题:https://www.cnblogs.com/GarrettWale/p/14386862.html 题目详情 ...
- Java基础 随笔整理
Java基础随笔整理 为了方便阅读,特整理了相关的学习笔记 Java感想 操千曲而后晓声 Java入门 Java其他 Java虚拟机详解 语言入门百题 Java开发工具 · Eclipse Java语 ...
- 免费报表工具 积木报表(JiMuReport)的安装
分享一b/s报表工具(服务),积木报表(JiMuReport),张代浩大佬出品. 官网:http://www.jimureport.com/ 离线版官方下载:https://github.com/zh ...
- AtCoder Beginner Contest 186
A Brick int n, m; int main() { scanf("%d%d", &n, &m); printf("%d\n", n / ...
- Linux目录,rpm及top,vi命令简记
一次简单的Linux常用操作记录 一.一些Linux目录结构 /bin 存放二进制可执行文件(ls.cat.mkdir等),一些常用的命令一般都在这里. /etc 存放系统管理和配置文件 /home ...
- JS逆向-抠代码的第一天【手把手学会抠代码】
首先声明,本人经过无数次摸爬滚打及翻阅各类资料,理论知识极其丰富,但是抠代码怎么都抠不会. 无奈之下,只能承认:这个活,需要熟练度. 本文仅对部分参数进行解析,有需要调用,请自行根据现实情况调整. 第 ...
- 2019 GDUT Rating Contest III : Problem E. Family Tree
题面: E. Family Tree Input file: standard input Output file: standard output Time limit: 1 second Memory ...
- 3.学习numyp的矩阵
Numpy提供了ndarray来进行矩阵的操作,在Numpy中 矩阵继承于NumPy中的二维数组对象,但是矩阵区别于数组,不可共用数组的运算规律 一.创建矩阵 import numpy as np m ...
- 【博弈论】组合游戏及SG函数浅析
目录 预备知识 普通的Nim游戏 SG函数 预备知识 公平组合游戏(ICG) 若一个游戏满足: 由两名玩家交替行动: 游戏中任意时刻,合法操作集合只取决于这个局面本身: 若轮到某位选手时,若该选手无合 ...