Spring boot 2.x 过滤器造成时间被转成毫秒数
Spring boot 2.x 过滤器造成时间被转成毫秒数
最近使用spring过滤器,但是发现date时间被转成了毫秒数,在此记录解决方案。
如若着急可拉至最后直接看:最终解决方案。
WebMvcConfigurerAdapter
Spring 2.0以前时继承WebMvcConfigurerAdapter来实现拦截器,但是在2.0以后此类被标记为废弃。所以经过搜索,推荐继承WebMvcConfigurationSupport类。
WebMvcConfigurationSupport
继承WebMvcConfigurationSupport类的实现代码如下:
package com.haier.qms.hce.hceservice.config;
import com.haier.qms.hce.hceservice.interceptor.UserLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 启用拦截器
*/
@SpringBootConfiguration
public class InterceptorConfig extends WebMvcConfigurationSupport{
@Autowired
private UserLoginInterceptor userLoginInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userLoginInterceptor)
//拦截规则
.addPathPatterns("/**")
//排除规则,即不拦截的访问
.excludePathPatterns("/target/**");
super.addInterceptors(registry);
}
}
userLoginInterceptor是我自己实现的一个拦截器,实现HandlerInterceptor接口,重写preHandle方法。
但是使用继承WebMvcConfigurationSupport类的方法实现拦截器,就造成了Date日期被转成了毫秒数。
解决Spring拦截器造成Date日期被转成了毫秒数
在Spring的配置文件中添加
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
但是不起作用,这是因为拦截器是继承了WebMvcConfigurationSupport类造成的。具体原因自行百度,在此不再赘述。
最终解决方案
实现WebMvcConfigurer接口来实现拦截器,同时配置上上面的配置项。具体代码如下:
package com.haier.qms.hce.hceservice.config;
import com.haier.qms.hce.hceservice.interceptor.UserLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 启用过滤器
*/
@SpringBootConfiguration
public class InterceptorConfig implements WebMvcConfigurer{
@Autowired
private UserLoginInterceptor userLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userLoginInterceptor)
//拦截规则
.addPathPatterns("/**")
//排除规则,即不拦截的访问
.excludePathPatterns("/target/**");
}
}
如有不解,可留言交流。