Issue
I want to pass in my parameters to my web service in the format:
Rather than
rel="noreferrer">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:
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.
Solution
How about the following way? I am using java.util.Optional class which acts as a wrapper over objects that can be null or not-null.
@RequestMapping
public Greeting greeting(@PathVariable Optional<String> name) {
String newName = "";
if (name.isPresent()) {
newName = name.get() //returns the id
}
return new Greeting(counter.incrementAndGet(),
String.format(template, newName));
}
Alternately, you can define two separate request mapping handlers:
@RequestMapping("/greeting")
public Greeting defaultGreeting()
AND
@RequestMapping("/greeting/{name}")
public Greeting withNameGreeting(@PathVariable String name)
Answered By - VHS
Answer Checked By - Mary Flores (JavaFixing Volunteer)