Spring MVC:在方法中获取RequestMapping值

时间:2013-05-06 07:49:28

标签: spring-mvc

在我的应用程序中,由于某些原因,我希望能够在相应的方法中获得@RequestMapping的值,但是,我找不到这样做的方法。以下是我想要的更多细节:

假设我有这样的方法:

@RequestMapping(value = "/hello")
@ResponseBody
public void helloMethod(AtmosphereResource atmosphereResource) {
...
}

我希望能够在方法中获得映射“/ hello”。我知道,我可以在映射中使用占位符,以便在实际请求到来时获取它们的值,但我需要一组有限的可处理请求,而我不需要if s或{{链1}}在我的方法中。

是否可能?

2 个答案:

答案 0 :(得分:3)

有效是一样的,不是吗?

private final static String MAPPING = "/hello";

@RequestMapping(value = MAPPING)
@ResponseBody
public void helloMethod(AtmosphereResource atmosphereResource) {
   // MAPPING accessible as it's stored in instance variable
}

但回答最初的问题:如果没有直接访问方法,我不会感到惊讶,很难想出在控制器代码中访问这些信息的正当理由(IMO注释的最大好处之一)控制器是你可以完全忘记底层的Web层,并使用普通的,不知道servlet的方法实现它们)

答案 1 :(得分:1)

您可以获得此方法的注释@RequestMapping,因为您可以获得任何其他注释:

 @RequestMapping("foo")
 public void fooMethod() {
    System.out.printf("mapping=" + getMapping("fooMethod"));
 }

 private String getMapping(String methodName) {
    Method methods[] = this.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName() == methodName) {
            String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
            if (mapping.length > 0) {
                return mapping[mapping.length - 1];
            }
        }
    }
    return null;
}

这里我明确传递方法的名称。如果绝对必要,请参阅讨论o如何获取当前方法名称:Getting the name of the current executing method