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?
This question is related to
java
spring
date
spring-mvc
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"
}
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!!
... 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
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.
Source: Stackoverflow.com