2012-04-20 176 views
9

我有一個奇怪的場景,其中不會調用我的控制器,除非我將調度器servlet映射到/ web.xml中。我已經定義了RequestMapping控制器:Spring MVC @RequestMapping不工作

@Controller 
public class UserController { 

    @RequestMapping(value = "/rest/users", method = RequestMethod.GET) 
    public ModelAndView getUsers(HttpServletRequest request) throws RestException { 
     ... 
    } 
} 

而且一個應用程序上下文:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" 
     xsi:schemaLocation=" 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

    <context:component-scan base-package="com.test.rest.controller" /> 

最後,這是在web.xml中映射:

<servlet> 
    <servlet-name>rest-servlet</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/restContext.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

<servlet-mapping> 
    <servlet-name>rest-servlet</servlet-name> 
    <url-pattern>/*</url-pattern> 
</servlet-mapping> 

可正常工作即我可以向/休息/用戶發出請求。但是,如果我改變web.xml中映射:

<servlet-mapping> 
    <servlet-name>rest-servlet</servlet-name> 
    <url-pattern>/rest/*</url-pattern> 
</servlet-mapping> 

我得到一個MVC錯誤:

WARN servlet.PageNotFound: No mapping found for HTTP request with URI [/rest/users] in DispatcherServlet with name 'rest-servlet'.

因爲錯誤指示請求被映射到調度員的servlet看來還真奇怪,但唯一改變的是servlet映射。

有沒有其他人遇到過這個?

回答

16

調度servlet是Spring MVC的主要servlet。它處理所有的請求,到達您的應用程序,並使用其自己的路由引擎將其分派給控制器。如果您將其更改爲

<url-pattern>/rest/*</url-pattern> 

那麼你的要求應該是這樣的rest/rest/users

常見的模式 - 允許調度servlet來處理所有傳入的請求(第一配置是有效的)

+0

由於安東,唯一的我面對的問題是我有其他servlet與MVC調度程序servlet(GWT stuff等)一起定義,所以我不想通過它來路由所有內容。我想我需要看看一些URL重寫選項 – 2012-04-20 17:32:42

+1

您可以在servlet聲明中定義一堆。在你的場景中,你可以將Spring MVC映射到/ rest並將你的控制器映射到/ users – Anton 2012-04-20 17:35:01

+0

明白了......它現在變得非常有意義,謝謝你的幫助 – 2012-04-20 20:47:25