Как получить значение requestmapping в контроллере?
В контроллере у меня есть этот код,
так или иначе, я хочу получить запрос Сопоставление значения "поиск".
Как это возможно?
@RequestMapping("/search/")
public Map searchWithSearchTerm(@RequestParam("name") String name) {
// more code here
}
Ответы
Ответ 1
Один из способов - получить его из пути сервлета.
@RequestMapping("/search/")
public Map searchWithSearchTerm(@RequestParam("name") String name, HttpServletRequest request) {
String mapping = request.getServletPath();
// more code here
}
Ответ 2
Если вам нужен шаблон, вы можете попробовать 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);
}
Ответ 3
Наличие контроллера типа
@Controller
@RequestMapping(value = "/web/objet")
public class TestController {
@RequestMapping(value = "/save")
public String save(...) {
....
}
}
Вы не можете получить контрольный запрос базы данных с использованием отражения
// 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];
Очевидно, что работает с одним запросом. Однозначное значение.
Надеюсь, что это поможет.
Ответ 4
@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
}
Ответ 5
Для Spring 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);
}