What is the need of <mvc:default-servlet-handler />
in Spring MVC
?
Using this handler
spring dispatcher will forward all requests to the default Servlet
. To enable the feature either you can use annotations or xml based configuration as below:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Or in XML:
<mvc:default-servlet-handler/>
What it will do?
The DefaultServletHttpRequestHandler
will attempt to auto-detect
the default Servlet
for the container
at startup time, using a list of known names for most of the major Servlet containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere). If the default Servlet has been custom configured with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then the default Servlet’s name must be explicitly provided as in the following example:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable("myCustomDefaultServlet");
}
}
Or in XML:
<mvc:default-servlet-handler default-servlet-name="myCustomDefaultServlet"/>
When should we use it? When exactly is it needed? Why should we use it?
When you want spring dispatcher to serve static resources
under the web root
using default servlet.
If we are using DefaultServletHttpRequestHandler
, then we can replace :
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
with :
<mvc:default-servlet-handler />
More you can explore here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…