简体   繁体   English

在Java控制器上,如何获取批注@RequestMapping(“ / getThisValueFromOtherClass”)的值?

[英]On Java Controller how to get the value of annotation @RequestMapping(“/getThisValueFromOtherClass”)?

On Java MVC Controller how to get the value of annotation @RequestMapping("/getThisValueFromOtherClass")? 在Java MVC Controller上,如何获取批注@RequestMapping(“ / getThisValueFromOtherClass”)的值? I know we can extract this by using java reflections but is there any other way? 我知道我们可以使用java反射来提取此内容,但是还有其他方法吗? Thank you. 谢谢。

@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. 如果只是为了避免在每个位置更改url,我建议在某个类中定义一个字符串常量,而不是在请求映射中使用硬编码的字符串,请在每个位置使用该常量。 In future if u want tp\\o change the url, simple update the constant value at one place 将来如果您想tp \\ o更改网址,只需在一个位置更新常数值

final String constUrl = "/myurl"; final String constUrl =“ / myurl”;

@RequestMapping(value=constUrl) @RequestMapping(值= 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);
}

To obtain the path, you should pass the Request ie HttpServletRequest as a parameter to your handler method. 要获取路径,您应该将Request即HttpServletRequest作为参数传递给处理程序方法。

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

Reference: 参考:

In your case if an URI pattern “/getThisString” is requested, it will map to this MyController , and handle the request with method where @RequestMapping(method = RequestMethod.GET) is declared. 在您的情况下,如果请求了URI模式“/getThisString” ,它将映射到此MyController ,并使用声明了@RequestMapping(method = RequestMethod.GET)方法来处理请求。

You can refer this tutorial @RequestMapping example 您可以参考本教程@RequestMapping示例

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM