Issue
Can I do something like this with Spring MVC ?
@RequestMapping(value = "/{root}")
public abstract class MyBaseController {
@PathVariable(value = "root")
protected ThreadLocal<String> root;
}
@Controller
public class MyController extends MyBaseController {
@RequestMapping(value = "/sayHello")
@ResponseBody
public String hello() {
return "Hello to " + this.root.get();
}
}
When I request to http://..../roberto/sayHello
, I get this as response:
Hello to roberto
Solution
You can have a path variable in the controller URL-prefix template like this:
@RestController
@RequestMapping("/stackoverflow/questions/{id}/actions")
public class StackOverflowController {
@GetMapping("print-id")
public String printId(@PathVariable String id) {
return id;
}
}
so that when a HTTP client issues a request like this
GET /stackoverflow/questions/q123456/actions/print-id HTTP/1.1
the {id}
placeholder is resolved as q123456
.
Answered By - Raffaele