I want to pass in my parameters to my web service in the format:
http://.../greetings/neil/1
Rather than
http://.../greetings?name=neil&id=1
So I changed my code from (note, I've only included the first parameter in the code):
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
to:
@RequestMapping
public Greeting greeting(@PathVariable String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
which works, however I do not know how to add default values to @PathVariable so that for example:
http://.../greetings/
http://.../greetings/neil/
would work as it does with query parameters.
How do I do this? I thought maybe it would pass null, but it just generates a page error.
I guess the answer might be to add multiple overloads, but that sounds a bit messy.
thanks.
thanks.
Spring 5 / Spring Boot 2 example:
@RequestMapping({"/greeting-blocking/{name}","/greeting-blocking/"})
public ResponseEntity<User> greetingBlocking(
@PathVariable(name = "name", required = false) String name) {
String username = StringUtils.isEmpty(name) ? "anonymous" : name;
return ResponseEntity.ok().body(User.create(username));
}
@RequestMapping({"/greeting-reactive/{name}","/greeting-reactive/"})
public Mono<ResponseEntity<User>> greetingReactive(
@PathVariable(name = "name", required = false) String name) {
String username = StringUtils.isEmpty(name) ? "anonymous" : name;
return userReactiveRepo.findByName(username).map(user -> ResponseEntity.ok().body(user));
}
One liner
@RequestMapping
public Greeting greeting(@PathVariable Optional<String> name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name.orElseGet(() -> "World")));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With