在控制器中,我有這個代碼, 不知何故,我想獲得請求映射值「搜索」。 這怎麼可能?如何獲取控制器中的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