SpringMVC日期参数转换问题Can not deserialize value of type java.util.Date from String "2018-07-19 15:59:34"

问题分析

报错日志

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserializevalue of type java.util.Date from Stringto parse Date value '2018-07-19 15:59:34': Can not parse date "2018-07-19 15:59:34": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', 
parsing fails (leniency? null))

问题分析:
前端传过来的日期格式为yyyy-MM-dd HH:mm:ss.SSS由于前端传递过来的是日期字符串格式的值,而SpringMVC无法将日期字符串格式的值解析为日期格式

解决方案一

新增一个类继承 org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter 父类 覆写父类的configureMessageConverters方法,增加MappingJackson2HttpMessageConverter类型的对象值

@Component
class WebConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List  < HttpMessageConverter  <   ?     >     >      converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(smt);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //设置中文编码格式
        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        converters.add(mappingJackson2HttpMessageConverter);
        super.configureMessageConverters(converters);
    }
}

方案二

 @Configuration
public class WebWeixinConfig {
    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(smt);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //设置中文编码格式
        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
        }
    } 

你可能感兴趣的:(#,SpringMVC)