Optional query parameters in Spring Boot
How to handle optional query parameters in spring boot? ohh it is just checking whether the parameter is null or not… Ohh gosh that is the old way. Let’s learn the smarter way.
Hello developers, Let’s start. There are several ways of handling optional parameters.
- By defining required attribute.
- Using java 8 optional feature.
Let’s go through both and understand concepts.
By defining required attribute.
In this case we specify that the particular query parameter is not required and we check whether it is null or not and do the rest.
@GetMapping("/test")
public ResponseEntity getTest(@RequestParam(required = false) String id) {
if (id == null) {
return new ResponseEntity("no query param", HttpStatus.OK);
} else {
return new ResponseEntity(id, HttpStatus.OK);
}
}
Using java 8 optional feature.
In this case we use java 8 optional feature as follows and for that we have to use the java.util.Optional
library.
@GetMapping("/test")
public ResponseEntity getTest(@RequestParam Optional<String> id) {
if(id.isPresent()) {
return new ResponseEntity(id.get(), HttpStatus.OK);
} else {
return new ResponseEntity("null", HttpStatus.OK);
}
}
Hopefully this is helpful.
If you have found this helpful please hit that 👏 and share it on social media :).