0
votes

My goal is to map /{any path} and *.html to a servlet without mapping /*. For example:

map:
/foo
/foobar/
/bar.html
/foo/bar.html

don't map:
/foo.js
/bar.pdf

In order to do this, I have a servlet and welcome file mapped like so:

web.xml:

<servlet-mapping>
 <servlet-name>someServlet</servlet-name>
 <url-pattern>*.html</url-pattern>
</servlet-mapping>

<welcome-file-list>
 <welcome-file>index.html</welcome-file>
</welcome-file-list>

and in a controller, I have

@RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView showPage(HttpServletRequest request){
  ...
}

this will not work - the servlet will not be triggered on /test. However, I've found that if I create a blank file at /test/index.html, then it does work - I assume the default servlet is somehow helping by finding the index.html.

Unfortunately, I can't rely on static files. Is there any way I can make this mapping work without the blank file hack and without mapping /* to the servlet?

1

1 Answers

2
votes

The answer depends on whether you want Spring to handle:

  • Only URLs ending in .html or without an extension, or
  • All URLs, except those ending in .js and .pdf, etc

Both those rules would match the list you gave in your question. However the second one is easier to implement. If you have a known list of extensions that you don't want Spring to handle, simply map those files in your web.xml file to the default handler like this:

<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>

However this only works if you know all the extensions you don't want Spring to handle, because you have to list each extension in web.xml.

If you really want to reject any extension other than .html then you need to override Spring's default behaviour somehow. I won't go in to that here because I think the above is a better option. But two possible ways of doing that are explained in this question: spring mvc how to bypass DispatcherServlet for *.html files?