在控制器中,我有这个代码, 不知何故,我想获得请求映射值“搜索”。 这怎么可能?如何获取控制器中的requestmapping值?
@RequestMapping("/search/")
public Map searchWithSearchTerm(@RequestParam("name") String name) {
// more code here
}
在控制器中,我有这个代码, 不知何故,我想获得请求映射值“搜索”。 这怎么可能?如何获取控制器中的requestmapping值?
@RequestMapping("/search/")
public Map searchWithSearchTerm(@RequestParam("name") String name) {
// more code here
}
一种方法是从servlet路径中获取它。
@RequestMapping("/search/")
public Map searchWithSearchTerm(@RequestParam("name") String name, HttpServletRequest request) {
String mapping = request.getServletPath();
// more code here
}
@RequestMapping("foo/bar/blub")
public Map searchWithSearchTerm(@RequestParam("name") String name, HttpServletRequest request) {
// delivers the path without context root
// mapping = "/foo/bar/blub"
String mapping = request.getPathInfo();
// more code here
}
如果你想要的图案,你可以尝试HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE
:
@RequestMapping({"/search/{subpath}/other", "/find/other/{subpath}"})
public Map searchWithSearchTerm(@PathVariable("subpath") String subpath,
@RequestParam("name") String name) {
String pattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
// pattern will be either "/search/{subpath}/other" or
// "/find/other/{subpath}", depending on the url requested
System.out.println("Pattern matched: "+pattern);
}
拥有一个像
@Controller
@RequestMapping(value = "/web/objet")
public class TestController {
@RequestMapping(value = "/save")
public String save(...) {
....
}
}
控制器,你不能使用反射
得到控制的基础requestMapping// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
与反射
或方法requestMapping(从一个方法内部)太
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(RequestMapping.class).value()[0];
显然与工作在requestMapping单个值。
希望这会有所帮助。
这在使用内部逻辑的抽象基本控制器时很有用,它需要继承,具体的控制器类的请求映射。 – 2017-02-28 14:52:31
RequestMapping不? http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html – vzamanillo 2017-03-29 07:32:51
春3.1及以上,你可以使用ServletUriComponentsBuilder
@RequestMapping("/search/")
public ResponseEntity<?> searchWithSearchTerm(@RequestParam("name") String name) {
UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest();
System.out.println(builder.buildAndExpand().getPath());
return new ResponseEntity<String>("OK", HttpStatus.OK);
}
你能在你的使用情况展开吗?我试图弄清楚你想要在这里得到什么,因为除了记录或使用完整路径之外,搜索似乎没有用,在这种情况下,你可以从请求中获取路径作为指示文件 – walnutmon 2010-09-27 20:18:59