Spring MVC URLs without .something extension

First of all, if this is a duplicate, I apologize. I searched quite a lot, but could not find much, and I suspect that I did not use the correct conditions ...

I am building a site with Spring MVC and using annotation driven configuration. What I would like to do is to have URLs that do not have an extension at the end (.html, .do, etc.). So they would look like http://www.mysite.com/account/create , which I know is what is traditionally done using mod_rewrite on Apache or using files without extensions. It seems that this can be done without using a rewrite mechanism (I know about the urlrewritefilter project), since Spring supports outputting parameters from the query string (see Section 15.3.2.1 in the documentation ), and the favorite store example does not seem to have extensions at the end of its Urls.

However, it seems that whenever I try to redirect all requests to the dispatcher servlet (my thinking on how to undo the need for something like *.htm ), I run into difficulties ... I can get it working (using the XML configuration I recently switched to annotation configuration) using only the standard "* .htm" for all pages.

My controller code looks like

 @Controller @RequestMapping("/home") public class HomeController { ... @RequestMapping(method = RequestMethod.GET) public ModelAndView get() { ... } 

And my web.xml looks like

  <servlet> <servlet-name>dispatch</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatch</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> 

Am I missing something? Is this possible without using a rewrite mechanism?

It should be noted that the above configuration does not work. It always returns error 404 ...

+4
source share
1 answer

Using URL patterns like /* is usually a bad idea, as the container forwards everything to the DispatcherServlet , including internal requests for the JSP. So when your controller returns the JSP name in ModelAndView , it will be returned to the DispatcherServlet again, giving you 404.

You either need to save the file extension in your paths, or you need some kind of prefix so that you can distinguish requestd for DispstcherServlet from requests for JSP.

+4
source

All Articles