I am new to Spring. I noticed that when handling static resources, there are two options available:
Option 1:
If Spring's DispatcherServlet
is mapped to /
with the below code, which makes it the "Default Servlet", it's possible to map certain static resources to Spring handlers with RequestMapping
annotation (overriding the AbstractAnnotationConfigDispatcherServletInitializer
class):
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
Then we can still enable the container's "Default Servlet" to handle those static resources whose URL pattern is not covered by Spring request mapping (overriding the WebMvcConfigurerAdapter
class):
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
This basically uses the servlet container's "Default Servlet" as the catch-all to handle all the static resources missed by Spring's DispatcherServlet
.
Option 2:
(overriding the WebMvcConfigurerAdapter
class)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("*.efi").addResourceLocations("/");
}
- Why are there two options?
- What are the main differences between these approaches?
- Are there any other options?
I usually take option 2 because I want to stick to Spring, but I know that's not a strong reason.
Some reference related to static resources handling:
- Serve Static Resources with Spring
- Spring Framework 4.1 - handling static web resources
- Spring MVC – How to include JS or CSS files in a JSP page
ADD 1
It seems option 2 provides much more flexibility regarding the resource mapping. And even resources within WEB-INF
folder can be mapped.
DispatcherServlet
to ``. – Whipstall