在 Java MVC 控制器上如何获取注解 @RequestMapping("/getThisValueFromOtherClass") 的值?我知道我们可以通过使用 java 反射来提取它,但是还有其他方法吗?谢谢你。
@RequestMapping("/getThisString")
public class MyController{}
在 Java MVC 控制器上如何获取注解 @RequestMapping("/getThisValueFromOtherClass") 的值?我知道我们可以通过使用 java 反射来提取它,但是还有其他方法吗?谢谢你。
@RequestMapping("/getThisString")
public class MyController{}
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
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);
}
要获取路径,您应该将请求(即 HttpServletRequest)作为参数传递给您的处理程序方法。
@RequestMapping(value={"/getThisString"}, method=RequestMethod.GET)
public String handlerMethod (Model model, HttpServletRequest request) throws Exception {
String getThatString = request.getServletPath();
....
}
参考: