2013-05-06 71 views
0

在我的應用程序中,由於某些原因,我希望能夠在相應的方法中獲得@RequestMapping的值,但是,我找不到一種方法來執行此操作。以下是關於我想要的更多詳細信息:Spring MVC:在方法中獲取RequestMapping值

想,我有這樣的方法:

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

我希望能夠得到映射輸入「/ hello」的方法中。我知道,我可以在映射中使用佔位符,以便在實際請求到達時獲取它們的值,但是我需要一組有限的可處理請求,並且我不希望在我的方法中使用連鎖的if s或switch es。

是否有可能?

回答

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不知道的方法實現它們)

+0

如何對控制器上的請求映射執行此操作? – trusktr 2014-03-16 05:48:45

+0

@trusktr,不要使映射'私人'和資格與類名稱。 '@RequestMapping(MyClass.MAPPING)'。儘管如此,我看到更少的觀點。 – 2015-12-13 22:54:07

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; 
} 

這裏我明確地傳遞方法的名字。請參閱有關如何獲取當前方法名稱的討論,如果在此處絕對需要:Getting the name of the current executing method