DEV Community

Elattar Saad
Elattar Saad

Posted on

Spring Boot optional request params

Sometimes the job description forces us into a scenario where the request param (or query params) are not always needed or required. The obvious way to get the job done is to check simply if the param is null or not. Let's try this and another smarter way using Optionals which come with Java since its version 8.

Method 1: Using required attribute

As simple as the following, we'll set the required attribute to false and check if there's a value in the associated variable:

@GetMapping("/params")
public String getWithParam(@RequestParam(required = false) String name){
    if(name == null){
        return "Hello Anonymous";
    }
    return "Hello "+name;
}
Enter fullscreen mode Exit fullscreen mode

Method 2: Using Java 8 Optionals

This time we'll be doing the same using Optionals:

@GetMapping("/params")
public String getWithParam(@RequestParam Optional<String> name){
    if(name.isPresent()){
        return "Hello "+name.get();
    }
    return "Hello Anonymous";
}
Enter fullscreen mode Exit fullscreen mode

Or even in an advanced way:

@GetMapping("/params")
public String getWithParam(@RequestParam Optional<String> name){
    return  "Hello "+ name.orElse("Anonymous");
}
Enter fullscreen mode Exit fullscreen mode

More articles Here.

Discussion (2)

Collapse
xrio profile image
Elattar Saad Author

Yees, thank you