I am developing a webapp using Spring MVC 3 and have the DispatcherServlet
catching all requests to '/' like so (web.xml):
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Now this works as advertised, however how can I handle static content? Previously, before using RESTful URLs, I would have caught all *.html for example and sent that to the DispatcherServlet
, but now it's a different ball game.
I have a /static/ folder which includes /styles/, /js/, /images/ etc and I would like to exclude /static/* from the DispatcherServlet
.
Now I could get static resources working when I did this:
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/</url-pattern>
</servlet-mapping>
But I want it to have nice URLs (the point of me using Spring MVC 3) not the landing page being www.domain.com/app/
I also don't want a solution coupled to tomcat or any other servlet container, and because this is (relatively) low traffic I don't need a webserver (like apache httpd) infront.
Is there a clean solution to this?
The Problem is with URLPattern
Change your URL pattern on your servlet mapping from "/" to "/*"
For java based spring configuration you can use the following
Using ResourceHandlerRegistry which stores registrations of resource handlers for serving static resources.
More Info @ WebMvcConfigurerAdapter which defines callback methods to customize the Java-based configuration for Spring MVC enabled via @EnableWebMvc.
In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)
That works for me
Regards
Ayub Malik
The URLRewrite is sort of a "hack" if you want to call it that. What it comes down to is, you're re-inventing the wheel; as there are already existing solutions. Another thing to remember is Http Server = Static content & App server = dynamic content (this is how they were designed). By delegating the appropriate responsibilities to each server you maximize efficiency... but now-a-days this is probably only a concern in a performance critical environments and something like Tomcat would most likely work well in both roles most of the time; but it is still something to keep in mind none the less.