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

人走茶凉 提交于 2021-01-21 07:26:06

问题


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

回答1:


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.




回答2:


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:

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




回答3:


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.



来源:https://stackoverflow.com/questions/32236441/how-to-access-a-pathvariable-of-a-controller-specified-at-class-level-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!