Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does configureDefaultServletHandling means?

I am trying to understand how does Spring MVC works, and I don't understand this part of code in my Spring configurations:

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

When this is in my WebContextApplication class, everything works fine and when it's not present everything works fine too. So what is the purpose of this method? Should my WebContextApplication class have this method? and why?

like image 548
Vercryger Avatar asked Apr 01 '15 16:04

Vercryger


1 Answers

As JB Nizet already tried to explain both are used to serve static resources.

So your question is that your Java based Spring configuration has

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) {     
    registry.addResourceHandler("/assets/**").addResourceLocations("/resources/bootstrap/"); 
}

then why do you need

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

or why <mvc:default-servlet-handler/> if you have

<mvc:resources mapping="/assets/**" location="/resources/bootstrap/" />

in terms of xml configuration.


To answer your question based on the requirements you have put you don't need to override configureDefaultServletHandling() as you have already overridden and provided your static resource mappings.

By overriding addResourceHandlers() method you are essentially asking ResourceHttpRequestHandler to serve the resources mentioned resource location.

However if you override configureDefaultServletHandling() and enabling it you are essentially asking default servlet (mapped to "/") to serve the resources. There are couple of things you need to take care here if you are using this. Quoting from docs -

This allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container’s default Servlet), while still allowing static resource requests to be handled by the container’s default Servlet. It configures a DefaultServletHttpRequestHandler with a URL mapping of "/**" and the lowest priority relative to other URL mappings.

This handler will forward all requests to the default Servlet. Therefore it is important that it remains last in the order of all other URL HandlerMappings. That will be the case if you use or alternatively if you are setting up your own customized HandlerMapping instance be sure to set its order property to a value lower than that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.

like image 135
Aniket Thakur Avatar answered Nov 07 '22 18:11

Aniket Thakur