How to access a PathVariable of a controller specified at class level in Spring?

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.


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 the result like this: enter image description here

and,you can use ModelAndView return msg value to the jsp or other html page.


According to the docs:

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html

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.