5

I am confused about the way the DefaultAnnotationHandlerMapping works.

In my web.xml I have

 <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/somePath/someWork</url-pattern>

    <url-pattern>/users</url-pattern>
    <url-pattern>/user/*</url-pattern>
  </servlet-mapping>  

I have the controller like this,

   @RequestMapping(value="/user/adduser", method={RequestMethod.POST})
    public void addAdmin(@ModelAttribute("myData") myData data) {

        System.out.println("We reached adduser controller");

    }

And in the jsp file i have

<form:form id="adduser" method="post" action="/user/adduser" commandName="myData">

This does not work. I get the error no handler mapping found for "/adduser" and 404 for the page "/user/adduser"

But in the .xml file if i mention

  <url-pattern>/user/adduser</url-pattern>

it works, or if i make the controller like,

  @RequestMapping(value="/adduser", method={RequestMethod.POST})

also works. When submitting the page it reaches the correct controller.

I am now confused the way the @ReuqestMapping works. When a request comes like "/user/adduser" from where it will start looking for the right class and the right method?

kalyan
  • 3,076
  • 1
  • 22
  • 29

1 Answers1

10

Spring will match against the pathInfo property of the HttpServletRequest.

If your web.xml specifies <url-pattern>/user/*</url-pattern>, then the pathInfo will be the path with the /user prefix removed, so the @RequestMapping has to be /adduser.

If web.xml specifies <url-pattern>/user/adduser</url-pattern>, then the pathInfo will be the full /user/adduser path, so @RequestMapping has to match against that.

This isn't done by Spring, but by the servlet container, and it can be a bit confusing at times.

You can mitigate against this by using wildcards in @RequestMapping, e.g.

@RequestMapping(value="**/adduser", method={RequestMethod.POST})
user987339
  • 10,519
  • 8
  • 40
  • 45
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Thanks for reply skaffman. This gives me the insight. Another relevant question. In the production environment people really do such mappings like *.do ? I have not seen any real example like this. – kalyan Apr 21 '11 at 11:37
  • 1
    @kalyan: `*.do` is a hangover from the bad old days of Struts. You still see it on "real" websites, though. – skaffman Apr 21 '11 at 11:39