Reputation: 4102
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
Upvotes: 19
Views: 17050
Reputation: 20885
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
.
Upvotes: 25
Reputation: 186
you can code like this:
@RequestMapping("/home/{root}/")
public class MyController{
@RequestMapping("hello")
public String sayHello(@PathVariable(value = "root") String root, HttpServletResponse resp) throws IOException {
String msg= "Hello to " + root;
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.println(msg);
out.flush();
out.close();
return null;
}
}
and,you can use ModelAndView
return msg
value to the jsp
or other html page.
Upvotes: 10
Reputation: 1034
According to the docs:
the PathVariable annotation is itself annotated with @Target(value=PARAMETER)
so it shouldn't be possible to be used the way you're saying as it's only applicable to method parameters.
Upvotes: 2