Spring MVC:在方法中获取RequestMapping值

pbgvytdp  于 7个月前  发布在  Spring
关注(0)|答案(3)|浏览(132)

在我的应用程序中,出于某些原因,我希望能够在相应的方法中获取@RequestMapping的值,但是,我找不到这样做的方法。下面是关于我想要的更多细节:
假设我有一个这样的方法:``

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

我希望能够在方法中获得Map“/hello”。我知道,我可以在Map中使用占位符,以便在实际请求到来时获得它们的值,但我需要有限的可处理请求集,并且我不希望在我的方法中有if s或switch es链。
有可能吗?

arknldoa

arknldoa1#

这将 * 有效地 * 是相同的,不是吗?

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不知道的方法来实现它们)

flmtquvp

flmtquvp2#

你可以像获取任何其他annotation一样获取这个方法的annotation @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;
}

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

axzmvihb

axzmvihb3#

如果有人想从类控制器@RequestMapping中获取路径,你可以尝试直接读取annotation:

private static String getControllerPath() {
        val annotation = IoaIntegrationController.class.getAnnotation(RequestMapping.class);
        val pathList = Objects.requireNonNullElse(annotation.value(), annotation.path());
        return pathList[0];
    }

相关问题