Search code examples
springrestspring-mvcurl-pattern

url-pattern doesn't work in spring mvc application


Spring 3.2 in apache tomcat

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>

rest-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>

My Controller:

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

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

When i call /localhost:8080/rest/person/test, i get 404 error (page not found).

However, when i change the url-pattern in web.xml file to:

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

it works fine.

How can i make the first url-pattern work??


Solution

  • Remove rest from your RequestMapping, e.g. change it to

    @RequestMapping(value = "/person")
    

    The reason for this is that your url-pattern already contains rest/*, so what you were doing was to map to the URL rest/rest/person/test and not rest/person/test.