Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 modeExit 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 modeExit fullscreen mode

Or even in an advanced way:

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

More articlesHere.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
daasrattale profile image
Elattar Saad
Your neighbourhood friendly coffee-powered Software Engineer. Spending a part of my lifetime working with @SpringFramework, @Golang and @NextJS.
  • Work
    Software Engineer
  • Joined

Yees, thank you

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Your neighbourhood friendly coffee-powered Software Engineer. Spending a part of my lifetime working with @SpringFramework, @Golang and @NextJS.
  • Work
    Software Engineer
  • Joined

More fromElattar Saad

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp