Search This Blog

Tuesday, 4 December 2012

Reading the date in the request parameter

In the previous posts we saw how Spring allows us to accept request parameters as method level parameters for our Controllers. This is all very easy when we are dealing with String parameters like "first name " or "address". But what if we have date of birth?
The user will input the date in a certain format. One way for the server to process it would be:
  1. Receive the date in a string parameter.
  2. Parse the string into a date object.
This code would have to be repeated in all your controller methods for all date fields. An alternative and more convenient technique is to create property editors.
The PropertyEditor may be defined as:
A PropertyEditor class provides support for GUIs that want to allow users to edit a property value of a given type. PropertyEditor supports a variety of different kinds of ways of displaying and updating property values. Most PropertyEditors will only need to support a subset of the different options available in this API.
Spring also uses this concept internally and has defined several property editors to convert from a display form to an Object and vice versa. One such editor is the CustomDateEditor.
To test the above editor, I created  a GET url with a date parameter:
"/date.do?date=22/09/2012"
The Controller for the same is"
@RequestMapping(value = { "/date.do" }, method = RequestMethod.GET )
public String process(Date date)
        throws Exception {
    System.out.println("date received is " + date);
    return "sucess";
}
Now to add the code to convert the string to a date class:
@Override
protected void initBinder(HttpServletRequest request,
        ServletRequestDataBinder binder) throws ServletException {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
As seen I had to add an overridden method. The method registers the custom editor that tells Spring to convert any date parameters into an actual Date object. For this to work the controller needs to extend the SimpleFormController class which provides the above method.
The class has been deprecated in newer version of Spring in favor of annotations. The annotation way of adding custom editors is:
@InitBinder
public void initBinder(final WebDataBinder binder) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
The WebDataBinder class binds the data between web request parameters and JavaBean objects. The ServletRequestDataBinder class that we used in the non-annotation based method is actually a subclass of WebDataBinder.

No comments:

Post a Comment