如何在Spring Boot WebMvcConfigurerAdapter中设置日期和日历的日期格式?

时间:2018-08-02 12:55:05

标签: spring-mvc spring-boot

我正在为WebMvcConfigurerAdapter使用以下自定义配置,以支持惰性对象,并同时支持XML和JSON响应:

@Configuration
@EnableWebMvc
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public MappingJackson2HttpMessageConverter jacksonJsonMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper mapper = new ObjectMapper();
        // Registering Hibernate5Module to support lazy objects
        mapper.registerModule(new Hibernate5Module());
        mapper.setDateFormat(dateFormat);
        messageConverter.setObjectMapper(mapper);
        return messageConverter;
    }

    public MappingJackson2XmlHttpMessageConverter jacksonXmlMessageConverter() {
        MappingJackson2XmlHttpMessageConverter messageConverter = new MappingJackson2XmlHttpMessageConverter();

        XmlMapper mapper = new XmlMapper();
        // Registering Hibernate5Module to support lazy objects
        mapper.registerModule(new Hibernate5Module());
        mapper.setDateFormat(dateFormat);
        messageConverter.setObjectMapper(mapper);
        return messageConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // Here we add our custom-configured HttpMessageConverter
        // To support XML
        converters.add(jacksonXmlMessageConverter());
        // To support JSON
        converters.add(jacksonJsonMessageConverter());
        // To support Resources (File Download)
        converters.add(new ResourceHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}

我能够按预期获取Calendar对象(时间戳)。即yyyy-MM-dd HH:mm:ss 但是我无法以“ yyyy-MM-dd”格式发布Date对象。

如何添加自定义配置以支持两种格式,即java.util.Date为“ yyyy-MM-dd”和java.util.Calendar为“ yyyy-MM-dd HH:mm:ss”?

0 个答案:

没有答案