Nero
Nero

Reputation: 602

Spring mvc servlet url does not map correctly

When I go to the first url, it calls my home() method in the controller but when I go to the second url it does not call my homeTest() method. Why is that?

I get 404 error.

http://localhost:9083/MYAPP/foo       ------ first url
http://localhost:9083/MYAPP/foo/bar  ------ second url

web.xml

<servlet>
        <servlet-name>springServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
        <servlet-name>springServlet</servlet-name>
        <url-pattern>/foo/*</url-pattern>
</servlet-mapping>

Controller:

@RequestMapping(value="/foo", method = RequestMethod.GET)
public String home(Model model){
    return "home";
}

@RequestMapping(value="/foo/bar", method = RequestMethod.GET)
public String homeTest(Model model){
    return "home";
}

Upvotes: 1

Views: 1119

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280167

You need to configure your RequestMappingHandlerMapping.

The official documentation goes into detail about handler mappings and some of their properties. The relevant one here is alwaysUseFullPath:

  • alwaysUseFullPath If true, Spring uses the full path within the current Servlet context to find an appropriate handler. If false (the default), the path within the current Servlet mapping is used. For example, if a Servlet is mapped using /testing/* and the alwaysUseFullPath property is set to true, /testing/viewPage.html is used, whereas if the property is set to false, /viewPage.html is used

In short, when trying to find a mapping for /foo/bar, it removes the part that was matched by the Servlet environment, the /foo, and only uses the /bar to find a handler. You have no handler mapped to /bar.

By setting the property above to true, it will use the full path.

You can configure this in a @Configuration annotated WebMvcConfigurationSupport subclass, by overriding requestMappingHandlerMapping

@Override
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
    RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
    handlerMapping.setAlwaysUseFullPath(true);
    return handlerMapping;
}

Or whatever mechanism is appropriate for your configuration (there's an XML equivalent for example).


There's a special case for the exact match of /foo. It's not particularly relevant here.

Upvotes: 4

gschambial
gschambial

Reputation: 1391

Just change:

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

To

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

Upvotes: -1

Related Questions