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;
}

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";
}

Or even in an advanced way:

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

More articles Here.


React to this article
and see more on Dev Community