2012-07-08 87 views
5

,我發現了以下情況例外,如果我使用多級網址類像@RequestMapping("/api/v0.1")發現:曖昧映射使用級多層次@RequestMapping URL時

java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'userController' 
bean method getUsers()|to {[/api/v0.1]}: There is already 'userController' bean 
method getUser(java.lang.String) mapped. 

這就像方法級映射不進入根本沒有考慮。
但是,如果我把@RequestMapping("/api")即刪除/v0.1部分也沒關係。

這裏是剝離到最小的情況下,配置:

@Controller 
@RequestMapping("/api/v0.1") 
public class UserController { 

    @RequestMapping(value = "/users") 
    @ResponseBody 
    public List<User> getUsers() { 
     return null; 
    } 

    @RequestMapping(value = "https://stackoverflow.com/users/{username}") 
    @ResponseBody 
    public User getUser(@PathVariable String username) { 
     return null; 
    } 
} 

的web.xml

<servlet-mapping> 
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

的servlet-context.xml中:

<!-- Configures the @Controller programming model --> 
<mvc:annotation-driven /> 

<!-- Forwards requests to the "/" resource to the "welcome" view --> 
<mvc:view-controller path="/" view-name="home"/>  

<!-- Handles HTTP GET requests for /assets/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory --> 
<mvc:resources mapping="/assets/**" location="/assets/" /> 

我使用的是春天3.1。我也嘗試將alwaysUseFullPath屬性設置爲RequestMappingHandlerMapping bean的屬性,但它沒有改變這種情況。

回答

2

非常有趣的問題 - 我檢查了可能發生的事情,你是對的,「v0.1」真的拋棄了org.springframework.util.AntPathMatcher,它通過組合來自控制器的路徑和來自映射的路徑來創建完整的URI路徑方法。如果它在Controller中看到一個「file.extension」類型的模式,那麼它完全忽略了該方法的路徑映射 - 這就是爲什麼您的@PathVariable被忽略的原因。

我不知道這是否是在Spring MVC,臨時的解決辦法是沿着你已經提到了哪些錯誤或預期的行爲 -

1.To從控制器的RequestMapping刪除「V0.1」和使其不帶擴展名說v0_1

2.To把這個映射的映射方法:「」

@Controller 
@RequestMapping("/api") 
public class UserController { 

    @RequestMapping(value = "/v0.1/users") 
    @ResponseBody 
    public List<User> getUsers() { 
     return null; 
    } 

    @RequestMapping(value = "/v0.1/users/{username}") 
    @ResponseBody 
    public User getUser(@PathVariable String username) { 
     return null; 
    } 
} 
+0

我記得在類級別(沒有點)嘗試'@RequestMapping(「/ api/v01」)並且沒有得到結果,但我會再試一次並讓你知道。謝謝。 – SelimOber 2012-07-08 15:53:26

+1

好吧,我確實嘗試了v0_1,它的工作原理。所以我正在用這個。 – SelimOber 2012-07-09 12:20:53

+0

由於AntPathMatcher允許正則表達式,我認爲如果你逃脫了這個點,它會起作用。例如。 'V0 \ .1' – jasop 2013-02-02 11:14:18

0

您應該使用@RequestMapping(value = "/{version:.*}/users")包括點在路徑變量