DEV Community

Elattar Saad
Elattar Saad

Posted on

5 1

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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
daasrattale profile image
Elattar Saad

Yees, thank you

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more