robert trudel
robert trudel

Reputation: 5749

Assign null for the default value in @RequestParam annotation

I use Spring Boot.

In a REST controller, is there a way when we use @RequestParamannotation to set default value to null for a string parameter?

Upvotes: 2

Views: 7040

Answers (2)

NeeruKSingh
NeeruKSingh

Reputation: 1585

No need to set null as initial value of String, because String default value is already null, but other values can be set using defaultValue in @RequestParam annotation.

Please, find below an example of using defaultValue:

@RestController  
@RequestMapping("/home")  
public class IndexController {

    @RequestMapping(value = "/name")
    String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {  
        return "Required element of request param";  
    }  
}

Upvotes: 0

glytching
glytching

Reputation: 47895

Spring's @RequestParam annotation supports:

  • required
  • defaultValue

So, a mapping like this ...

@GetMapping(value = "/{first}")
public ResponseEntity<String> doSomething(@PathVariable int first, @RequestParam(required = false) String foo) {

    // ...
}

... defines a request param named foo which is optional and for which null (because null is the unitialised state for a String object) will be provided by Spring if the caller does not pass this param.

Upvotes: 5

Related Questions