2015-11-13 44 views
0

鑑於等的方法:是否可以引用註釋方法中的@RequestMapping值?

@RequestMapping(value = {"/foo"}, method = RequestMethod.GET) 
public String getMappingValueInMethod() { 
    log.debug("requested "+foo); //how can I make this refer to /foo programmatically? 
    return "bar"; 
} 

用例是用於重構一些過長的代碼。我有幾個GET方法做大致相同的事情,只有請求映射值是不同的。

我已經看過使用路徑變量,但這不是我真正想要的(除非有一些巧妙的用法,我沒有看到)。我也可以從HttpServletRequest中獲得價值,如this post,但不確定是否有更好的方法。

+1

當你說'我看過使用路徑變量,但這不是我真正想要的',你確定。 「@RequestMapping(value = {」/ {path}「},method = RequestMethod.GET) public String getMappingValueInMethod(@PathVariable(」path「)String path){ log.debug(」requested「 +路徑); 返回「bar」; }' –

+0

請詳細瞭解您的使用案例。 –

+0

對不起 - 看起來喬治提出的解決方案將起作用。將關閉這個問題。 – bphilipnyc

回答

1

溶液1

隨着HttpServletRequest

@RequestMapping(value = "/foo", method = RequestMethod.GET) 
public String fooMethod(HttpServletRequest request) { 
    String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString(); 
    System.out.println("path foo: " + path); 
    return "bar"; 
} 

溶液2

隨着reflection

@RequestMapping(value = "/foo2", method = RequestMethod.GET) 
public String fooMethod2() { 
    try { 
     Method m = YourClassController.class.getMethod("fooMethod2"); 
     String path = m.getAnnotation(RequestMapping.class).value()[0]; 
     System.out.println("foo2 path: " + path); 
    } catch (NoSuchMethodException e) { 
     e.printStackTrace(); 
    } 

    return "bar"; 
} 

如果你想要得到的類(而不是方法)的路徑,你可以使用:

String path = YourClassController.class.getAnnotation(RequestMapping.class).value(); 

解決方案3

隨着@PathVariable

@RequestMapping(value = {"/{foo3}"}, method = RequestMethod.GET) 
    public @ResponseBody String fooMethod3(@PathVariable("foo3") String path) { 
     path = "/" + path; // if you need "/" 
     System.out.println("foo3 path: " + path); 
     return "bar"; 
    } 
0

這樣做最簡單的方法是將數組直接放在請求映射我假設這是你想要的。

@RequestMapping(value = {"/foo","/foo1","/foo2"}, method = RequestMethod.GET) 
public String getMappingValueInMethod(HttpServletRequest request) { 
    log.debug("requested "+request.getRequestURI()); 
    return request.getRequestURI(); 
} 

然後命名JSP文件類似URI或其他明智的你可以存儲請求URI,在數據庫頁面的名稱之間的映射。

相關問題