2

在 Java MVC 控制器上如何获取注解 @RequestMapping("/getThisValueFromOtherClass") 的值?我知道我们可以通过使用 java 反射来提取它,但是还有其他方法吗?谢谢你。

@RequestMapping("/getThisString")
public class MyController{}
4

4 回答 4

2

If the purpose is just to avoid changing the url at every place, I will suggest define a string constant in some class and instead of using hard coded string in request mapping use that constant every where. In future if u want tp\o change the url, simple update the constant value at one place

final String constUrl = "/myurl";

@RequestMapping(value=constUrl)

you can make the constant static, if defining in another class

于 2013-11-09T13:55:10.633 回答
2

The value of the annotation can be read programmatically:

@RequestMapping("/endpoints")
public ResponseEntity<String> getPath() {
    String path = getClass().getAnnotation(RequestMapping.class).value()[0];
    return new ResponseEntity<String>(path, HttpStatus.OK);
}
于 2015-03-11T18:25:50.243 回答
1

要获取路径,您应该将请求(即 HttpServletRequest)作为参数传递给您的处理程序方法。

@RequestMapping(value={"/getThisString"}, method=RequestMethod.GET)
public String handlerMethod (Model model, HttpServletRequest request) throws Exception {             
   String getThatString = request.getServletPath(); 
   ....
}

参考:

于 2013-11-09T13:40:20.007 回答
0
于 2013-11-09T13:52:14.183 回答