user666
user666

Reputation: 2013

Spring boot @DateTimeFormat on required query parameters

When using @DateTimeFormat annotation to format a date sent as query parameter (@RequestParam), it automatically converts empty strings (received as date) to null without throwing type mismatch exception. This works fine when a date parameter is optional, however, when required = true is set, the @DateTimeFormat accepts the empty string and converts it to null without throwing an exception thus the required = true spring attribute is not considered. Is this a normal behavior from Spring? Are there any attributes that we can pass to @DateTimeFormat to choose if empty strings are acceptable or not?

@RequestParam(required = true) @DateTimeFormat(pattern ="yyyy-MM-dd") Date inputDate
        

Upvotes: 1

Views: 3494

Answers (2)

Max Farsikov
Max Farsikov

Reputation: 2763

Try using java.time.LocalDate without any @DateTimeFormat.

java.util.Date is outdated and java.time.* is intended to replace it.

LocalDate uses the ISO8601 format by default, and it is matched with your 'yyyy-mm-dd'. Also, its parse method throws an exception on an empty string.

Upvotes: 2

Kaj Hejer
Kaj Hejer

Reputation: 1040

I have tried to reproduce your issues with the following code with spring boot 2.4.4:

@GetMapping("/")
@ResponseBody
public String demo(@RequestParam(required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date inputDate) {
   System.out.println("inputDate: " + inputDate);
   return inputDate.toString();
}
  1. The url http://localhost:8080/?inputDate=2021-03-01 gives Mon Mar 01 00:00:00 CET 2021 in the browser
  2. The url http://localhost:8080/?inputDate= and http://localhost:8080/gives There was an unexpected error (type=Bad Request, status=400).in the browser and Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Date parameter 'inputDate' is not present] in the log
  3. The url http://localhost:8080/?inputDate=x gives There was an unexpected error (type=Bad Request, status=400). in the browser and Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date' in the log.

From your question I understand this is what you want.

Can you please clearify if I have misunderstood your question or else see if your can reproduce my result and see if they give the behaviour you want?

Upvotes: 1

Related Questions