0

I have a date DTO:

public class SampleDTO{
    Date date;
    //setter, getter, constructor
}

In Spring MVC, I make it in ModelAttribute and sent:

@ModelAttribute("sample")
public SampleDTO getSample() {
    return new SampleDTO(new Date());
}

However, In web page, it shows in following date format:

Thu Aug 31 00:00:00 CEST 2017

Anyone know how to change the date format?

PS: No any change in front-end, no use JSTL, no use tag. I only want to make some change in MappingJackson2HttpMessageConverter

vincent zhang
  • 444
  • 5
  • 20
  • How is Jackson relevant here? how is the date being printed by the web page? What are you using to generate the HTML? – JB Nizet Sep 01 '17 at 10:05
  • @JBNizet , not sure that if you could see my answer. What I mean is, as you know, Spring MVC use message converter to to handler HttpInputMessage and HttpOutputMessage, so MappingJackson2HttpMessageConverter is one of the converters. What I want is when Spring MVC out put to front web, it already into String, with date format I customize. – vincent zhang Sep 01 '17 at 13:12
  • @JBNizet , I use Thymeleaf, I know it could use Thymeleaf internal function, but I don't want – vincent zhang Sep 01 '17 at 13:13
  • Jackson is completely irrelevant if you just store an object in the model,a nd then use thymeleaf to render a HTML page displaying the properties of this model object. Jackson is used when you create Rest Controller, returning objects that are serialized to JSON using Jackson. You're not doing that. You want to format a date in a Thymeleaf template, so you need to read the Thymeleaf documentation. – JB Nizet Sep 01 '17 at 13:15

1 Answers1

0

You can config configure message converters in your configuration file:

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
    }
}
Maxim Kasyanov
  • 938
  • 5
  • 14