url-pattern在spring mvc应用程序中不起作用

时间:2014-06-22 20:55:12

标签: spring rest spring-mvc url-pattern

Spring apache tomcat中的3.2。

的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

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

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

其余-servlet的context.xml中:

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

    <annotation-driven />

    <context:component-scan base-package="com.*" />

</beans:beans>

我的控制器:

@Controller
@RequestMapping(value = "/rest/person")
public class PersonController {

    @RequestMapping(value = "/test")
    @ResponseBody
    public String getTest() {
        return "Test controller";
    }
}

当我调用/ localhost:8080 / rest / person / test时,我收到404错误(找不到页面)。

但是,当我将web.xml文件中的url-pattern更改为:

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

它工作正常。

如何让第一个url-pattern工作?

1 个答案:

答案 0 :(得分:4)

从您的RequestMapping中移除rest,例如将其更改为

@RequestMapping(value = "/person")

原因是您的url-pattern已包含rest/*,因此您要做的是映射到网址rest/rest/person/test而不是rest/person/test