Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
LittleLebowski Avatar asked Mar 01 '13 18:03

LittleLebowski


People also ask

How do you pass a date as a spring boot parameter?

We can also use our own conversion patterns by providing a pattern parameter in the @DateTimeFormat annotation: @PostMapping("/date") public void date(@RequestParam("date") @DateTimeFormat(pattern = "dd. MM. yyyy") Date date) { // ... }

How do you pass a date as a URL parameter?

To pass the datepicker field using URL parameters, you must set your datepicker field to disable lite mode. Please give it a try and let us know how it goes.

How do you pass a date in request param in Postman?

format(("YYYY-MM-DD"))); {{$timestamp}} -> predefined variable gets the current timestamp, Since you need date the above one should work. use the parameter {{currentdate}} in your GET request. If you are having a different issue, kindly provide more details.

How do you pass a date as a parameter in Java?

Call the format() method of DateFormat class and pass the date object as a parameter to the method.


2 Answers

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.

like image 175
LittleLebowski Avatar answered Sep 21 '22 17:09

LittleLebowski


This is what I did to get formatted date from front end

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)   @ResponseBody   public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {    return OK;   } 

You can use it to get what you want.

like image 35
AbdusSalam Avatar answered Sep 20 '22 17:09

AbdusSalam