Beto Neto
Beto Neto

Reputation: 4102

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

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

Answers (3)

Raffaele
Raffaele

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

JJ_Jacob
JJ_Jacob

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

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

Upvotes: 10

Alfonso Presa
Alfonso Presa

Reputation: 1034

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.

Upvotes: 2

Related Questions