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.

原文链接:Spring Boot optional request params

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容