前言:
在做的项目数据库所有日期,时间都是用datetime存储,所以实体类对应的类型就改为了LocalDateTime在Controller层用实体类接受时出现错误,大致意思就是String 不能转换成 LocalDateTime 。然后这篇文章就是为了解决这个问题。
解决:
Spring Mvc 可以配置很多转换器,所以我们自己先写个转换器
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 转换日期
* @author xia17
* @date 2019/5/25 14:52
*/
@Slf4j
public class DateConverter implements Converter<String,LocalDateTime> {
@Override
public LocalDateTime convert(String s) {
if (s==null || "".equals(s)){
return null;
}
try {
LocalDate parse = LocalDate.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return parse.atStartOfDay();
}catch (RuntimeException e){
log.error("参数转换Date异常:"+ e.getMessage());
}
try {
return LocalDateTime.parse(s,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}catch (RuntimeException e){
log.error("参数转换DateTime异常"+ e.getMessage());
throw new RuntimeException("在Controller转换日期格式时发生错误");
}
}
}
注意:LocalDateTime不能直接用 yyyy-MM-dd转换,要先转化成LocalDate.
然后在Mvc配置中加入转换。
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** mvc配置类
* @author xia17
* @date 2019/5/25 14:57
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加转换器
* @param registry
*/
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
这样就可以了。 好像是 springmvc 的配置类只有一个会生效 , 所以可以使用下面这种方式
另外一种配置方式 继承 WebMvcConfigurationSupport
package com.qxamoy.basedata.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.qxamoy.basedata.aspect.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.ArrayList;
import java.util.List;
/**
* 拦截器配置类
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport
{
/**
* 添加 访问参数的 转化器 这里加的日期转化
* @param registry 参数格式化注册器
*/
@Override
protected void addFormatters(FormatterRegistry registry){
registry.addConverter(new DateTimeConverter());
registry.addConverter(new DateConverter());
registry.addConverter(new BooleanConverter());
}
}