Search code examples
javaspringdatespring-mvc

How to accept Date params in a GET request to Spring MVC Controller?


I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows:

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) {
        //Content goes here
}

The request is sent correctly as I'm checking with Firebug. I get the error:

HTTP Status 400: The request sent by the client was syntactically incorrect.

How can I make the controller accept this format of Date? Please help. What am I doing wrong?


Solution

  • Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.

    @RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
            //Content goes here
    }
    

    Yes, it's simple. Just add the DateTimeFormat annotation.