WestFarmer
WestFarmer

Reputation: 765

Spring mvc, why my controller not mapped

I defined my Dispatcher servlet's url mapping in web.xml like this:

<servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>*.do</url-pattern>
 <url-pattern>/data/*</url-pattern>
</servlet-mapping>

my controller's method is annotated with:

@RequestMapping(value="/data/sys/CodeCatalogs")

when I request the url in browser I got 404 error, if I change the mapping to this:

@RequestMapping(value="/sys/CodeCatalogs")

the full url:

http://localhost:8080/cwe/data/sys/CodeCatalogs

it works, why? I am new to spring mvc, please help.

I tested url that contain no wildcard:

<servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
     <url-pattern>*.do</url-pattern>
     <url-pattern>/data/*</url-pattern>
     url-pattern>/test/foo</url-pattern>
    </servlet-mapping>

then this request mapping will works:

@RequestMapping(value="/test/foo")

Upvotes: 1

Views: 2156

Answers (2)

Kunal Surana
Kunal Surana

Reputation: 659

<servlet-mapping>
     <servlet-name>dispatcher</servlet-name>
     <url-pattern>*.do</url-pattern>
     <url-pattern>/data/*</url-pattern>
</servlet-mapping>

In the preceding example, all requests starting with /data and anything which ends with *.do will be handled by the DispatcherServlet instance named dispatcher.

So for controller's method is annotated with:

@RequestMapping(value="/data/sys/CodeCatalogs")

http://localhost:8080/cwe/data/sys/CodeCatalogs - Does not match
http://localhost:8080/cwe/data/data/sys/CodeCatalogs - Does matches

URL passes from browser will be first matched against URL pattern specified and then the URL specified in @RequestMapping.

For controller's method is annotated with :

@RequestMapping(value="/test/foo")

http://localhost:8080/cwe/test/foo - Matches since URL matches the exact pattern which is allowed as per Servlet Specification.
http://localhost:8080/cwe/data/test/foo  - This will also match because of pattern /data/*

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

For an incoming request of the form /data/sys/CodeCatalogs, your servlet container will consume the /data/ portion before passing the pattern to your Spring servlet. So the controller will receive /sys/CodeCatalogs and hence this is why your second @RequestMapping works and the first does not.

Upvotes: 1

Related Questions