0

I am specifying the property editors for my controller as :

@InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
        binder.registerCustomEditor(Date.class, editor);
    }

which work fine until I call the following method in an AJAX call.

@RequestMapping(value = "searchCriteria", method = RequestMethod.GET)
    public @ResponseBody Set<SearchCriteria> loadSearchCriterias(){
        // call service method to load criterias
        Set<SearchCriteria> criterias = new HashSet<SearchCriteria>();
        SearchCriteria sampleCriteria = new SearchCriteria();
        sampleCriteria.setStartDate(new Date());
                criterias.add(sampleCriteria);
        return criterias;
         }

In this case, the due date in SearchCriteria is not being converted to the proper format by the custom property editor. How can I make property editors to be applied even when I am returning an object through an AJAX call ?

public class SearchCriteria{
    Date startDate;
    String name;
    // getter setters
}
Daud
  • 7,429
  • 18
  • 68
  • 115

1 Answers1

1

I don't think it is possible to apply property editor for the returned values. Spring has a converter mechanism for it.

If you returning json and if you have Jackson in your classpath then spring will use it to convert the object to response string.
If you returning xml and if you have JAXB in your classpath then spring will use it to convert the object to response string.

If you are using Jackson library with spring then you need to tell jackson how you want to serialize the field by using serializer.

Ex:

public class DateTimeSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        if (value != null) {
            SimpleDateFormat f = new SimpleDateFormat(format);
            jgen.writeString(f.format(value));
        }
    }

}

Then annotate your field like

@JsonSerialize(using = DateTimeSerializer.class)
private Date createdDate;

If you want to use this globally you can try the mechanism explained here.

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks, but how to configure the jackson serializer for use with this class ? – Daud Feb 01 '13 at 12:39
  • can you share your `SearchCriteria`? – Arun P Johny Feb 01 '13 at 12:43
  • added the class. I guess adding the annotation to the createdDate field will automatically force Spring to search for the DateTimeSerializer anywhere in the classpath (or do we have to specify it somewhere ?) – Daud Feb 01 '13 at 12:49