I am pretty new in Spring and I am working on a Spring MVC application.
Into the servlet-context.xml configuration file I found these lines:
<!-- resources exclusions from servlet mapping -->
<mvc:resources mapping="/assets/**" location="classpath:/META-INF/resources/webjars/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/img/**" location="/img/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
The comment say resources exclusions from servlet mapping.
What exactly means these lines? I know that this servlet-context.xml should contain the DispatcherServlet configuration that handle the MVC behavior (and it is pretty clear for me) but what exactly does the previous lines?
Can you explain me in details the meaning and the previous syntax?
If you consider a spring mvc configuration where all the requests are mapped to a DispatcherServlet
, you can categorize those requests as requests for static and dynamic resources.
The requests for dynamic resources are matched by what you program inside your controller methods, and they are the subject of the typical framework processing such as path matching, content negotiation, validation, binding, conversion, formating, argument resolving.
The requests for static resources are the requests for .js, .css, or some other resources that are not getting created rather already exist deployed with your application. They are not handled by the programmatic controller methods rather by the ResourceHttpRequestHandler
, simply because they have a completly different set of processing actions comparing to dynamic request (apart from path matching). You can define the location of static files for the given mapping (this can be the classpath, some other webapp folder or a file system), caching strategy for the resource, transformations (such as modyfing links in css, tranforming LESS to CSS)
So its not really that you don't want the static resources to be handled by the servlet, in fact you can get a lot of possibilities and flexibility by doing so, check for example handling static web resources it is just that static and dynamic requests are a subject of different kind of actions, and by using mvc:resources
tag, you designate by mappings which requests are to be handled as static requests
As resources like images, css, javascript etc. are not supposed to be handled by servlet and to be specific by Dispatcherservlet, spring provides a way to specify them using
mvc:resources
tag. If such resource is not mapped using above tag, requested path will be used by dispatcher servlet to find a controller with matching request mapping.
But with the tag, spring looks into location attribute of tag to find and return the resource and if the resource is not found, HTTP status code 404 is returned.
Other helpful answers
Nice explanation of location attribute of the tag here
spring-3-mvc-resources-and-tag-mvcresources