Peter Rader Peter Rader - 1 month ago 19
reST (reStructuredText) Question

Spring RESTful Date format

A rest controller in jdk8 like this

@Transactional
@RequestMapping(value="/A", method = RequestMethod.POST)
public ABean aInsert(final java.sql.Date when, final long company) {
A bean = new A();
bean.setWhen(when);
bean.setCompany(entityManager.find(Company.class, company));
entityManager.persist(bean);
return new ABean(bean.getId(), bean.getVersion(), bean.getWhen(), bean.getCompany().getId());
}


is called with form post-data

when=1459987200000&company=1


but can not be called and returns a
400 - bad request
(description The request sent by the client was syntactically incorrect.)
.

My question is:


  • What is the default input string format of the
    java.sql.date
    ?


Answer

when=2016-04-21&company=10 Works, so its

yyyy-mm-dd

For every other format register a custom Converter like this:

@Autowired
private final ConfigurableConversionService conversionService=null;

@PostConstruct
public void registerConverter() {
    conversionService.addConverter(new Converter<String, Long>() {
        @Override
        public Long convert(String source) {
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm");
                return df.parse(source).getTime();
            } catch (ParseException e) {
                return Long.parseLong(source);
            }
        }
    });
}
Comments