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

JavaSpringDateSpring Mvc

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:

spring.mvc.date-format=yyyy-MM-dd

Solution 4 - Java

Below solution perfectly works for spring boot application.

Controller:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
	return userRepository.getAllInactiveUsers(dateTime);
}

So in the caller (in my case its a web flux), we need to pass date time in this("yyyy-MM-dd HH:mm:ss") format.

Caller Side:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
	Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
			.uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
			.bodyToFlux(User.class).map(UserDto::of);
	return userDto;
}

Repository:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);

Cheers!!

Solution 5 - Java

If you want to use a PathVariable, you can use an example method below (all methods are and do the same):

//You can consume the path .../users/added-since1/2019-04-25
@GetMapping("/users/added-since1/{since}")
public String userAddedSince1(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

//You can consume the path .../users/added-since2/2019-04-25
@RequestMapping("/users/added-since2/{since}")
public String userAddedSince2(@PathVariable("since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date since) {
    return "Date: " + since.toString(); //The output is "Date: Wed Apr 24 19:00:00 COT 2019"
}

//You can consume the path .../users/added-since3/2019-04-25
@RequestMapping("/users/added-since3/{since}")
public String userAddedSince3(@PathVariable("since") @DateTimeFormat(pattern = "yyyy-MM-dd") Date since) {
    return "Date: " + since.toString(); //The output is "Date: Thu Apr 25 00:00:00 COT 2019"
}

Solution 6 - Java

You can use :

public @ResponseBody String fetchResult(@RequestParam("from")@DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) { //Your code...

}

Solution 7 - Java

2000-10-31T01:30:00.000-05:00 convert to Datetime (Joda)

@GetMapping("test/{dateTimeStart}")
public void getCheckDaily2(
        @PathVariable(value = "dateTimeStart", required = false)
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
                DateTime dateTimeStart){

body here...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLittleLebowskiView Question on Stackoverflow
Solution 1 - JavaLittleLebowskiView Answer on Stackoverflow
Solution 2 - JavaAbdusSalamView Answer on Stackoverflow
Solution 3 - JavaPaul TView Answer on Stackoverflow
Solution 4 - JavaAman GoelView Answer on Stackoverflow
Solution 5 - JavaDavid JesusView Answer on Stackoverflow
Solution 6 - JavaSourabh BhavsarView Answer on Stackoverflow
Solution 7 - JavaHoiama RodriguesView Answer on Stackoverflow