【问题标题】:Spring MVC: get RequestMapping value in the methodSpring MVC:在方法中获取RequestMapping值
【发布时间】:2013-05-06 07:49:27
【问题描述】:

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

假设,我有一个这样的方法:

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

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

有可能吗?

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    实际上是一样的,不是吗?

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

    【讨论】:

    • 控制器上的请求映射如何做到这一点?
    • @trusktr,不要进行映射 private 并用类名限定它。 @RequestMapping(MyClass.MAPPING)。不过,我认为这样做更没有意义。
    【解决方案2】:

    您可以像获取任何其他注释一样获取此方法的注释@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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2015-11-18
      • 2013-10-19
      相关资源
      最近更新 更多