Spring Converters - Tuong-Nguyen/Spring GitHub Wiki
Spring introduces a simple Converter interface that can convert request String values to Controller method parameter values of any Object
Implement Converter<String, T> and override convert() method. String can be converted to the T return type.
public class VNDateConverter implements Converter<String, Date> {
@Override
public Date convert(String strDate) {
Date tmpDate = null;
try{
System.out.println("Converting VNDate");
tmpDate = new SimpleDateFormat("dd/MM/yyyy").parse(strDate);
} catch (ParseException e){
e.printStackTrace();
}
return tmpDate;
}
}In WebConfig file, override addFormaters() method and add Converter.
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(vnDateConverter());
}With above declaration, application will automatically convert all values from request in String to Date if data type of that field in model is Date.