Reputation:
My dispatcher servlet maps to the root of the app.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have a folder called 'static' in my webroot. It contains CSS, JS and image files. However, because of the dispatcher servlet mapping, the requests for static contents end up in 404s.
I know the solutions lying around to address this.
Make dispatcher map to a more specific URL, say :context:/app/, and then write a filter to intercept requests, and map conditionally to the default servlet, or else delegate to the spring dispatcher.
The URL rewrite trick.
using <mvc:resources />
Problem is, my mappings are XML based, and I will absolutely not scatter my mappings config all over the place in the name of using annotations. So if I use <mvc:resources />
, my xml based mappings break, and all url mappings to different controllers are lost.
This is becase <mvc:resources /
> overrides some settings and applies its own. But it is also the cleanest solution for static content.
Any way available to tell <mvc:resources />
to not override my xml based mappings?
Upvotes: 1
Views: 3345
Reputation: 724
add <mvc:default-servlet-handler/> towards the top of your web.xml file
or if you are you using annotations
@Configuration
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable("default");
}
}
Upvotes: 0
Reputation: 331
I do have this in the web.xml
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
Upvotes: 1
Reputation: 1456
<mvc:resources />
appears to be a perfect fit for your problem.
From what I understand, your DispatcherServlet
is handling all requests to your server. So the resource tag should return the files at the location specified in the mvc:resources location attribute. It should not be catching anything other than what's mapped.
Are you using something along the lines of
<mvc:resources mapping="/static/**" location="/static/"/>
If it is overriding settings that aren't configurable in the tag consider instantiating your own org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Upvotes: 1
Reputation: 29619
You can provide a file extention for your controllers, e.g.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Then all URLs ending in .do
will go through springs DispatcherServlet.
Upvotes: 0