Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring set default PathVariable

Tags:

spring

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.

like image 814
Neil Walker Avatar asked Jan 12 '17 18:01

Neil Walker


2 Answers

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));
}
like image 162
kinjelom Avatar answered Sep 21 '22 09:09

kinjelom


One liner

    @RequestMapping
    public Greeting greeting(@PathVariable Optional<String> name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name.orElseGet(() -> "World")));
    }
like image 35
Emmanuel Osimosu Avatar answered Sep 21 '22 09:09

Emmanuel Osimosu