What is the difference between DispatcherServlet
and ContextLoaderListener
in Spring framework? Do we need to configure both of them in web.xml when we are using spring framework?
Spring web applications have 2 application contexts. DispatcherServlet loads beans containing web components such as controllers, view resolvers, handler mappings, etc. ContextLoaderListener loads the other beans in the application that are typically used by service and data access layers.
ContextLoaderListner is a Servlet listener that loads all the different configuration files (service layer configuration, persistence layer configuration etc) into single spring application context. This helps to split spring configurations across multiple XML files.
The DispatcherServlet is the front controller in Spring web applications. It's used to create web applications and REST services in Spring MVC. In a traditional Spring web application, this servlet is defined in the web. xml file.
You can have as many DispatcherServlets as you want. Basically what you need to do is duplicate the configuration and give the servlet a different name (else it will overwrite the previous one), and have some separate configuration classes (or xml files) for it.
AFAIK each DispatcherServlet
will have a WebApplicationContext
. By default the DispatcherServlet
looks for a spring configuration file named [appname]-servlet.xml
under WEB-INF
folder.
Do we need to configure
DispatcherServlet
?
Yes, every spring application should configure DispatcherServlet
as it is the one through which all the requests are routed. It decides the appropriate method of the controller class to handle the request. Once controller returns the model
along with the logical view, DispatcherServlet
takes the help of ViewResolver
to resolve the view
(generally JSPs) and will pass the model
data to the view, which is finally rendered on the browser.
Do we need to configure
ContextLoaderListener
?
No, this is not mandatory. Spring applications can live with out ContextLoaderListener
.
Why do we need
ContextLoaderListener
?
Usually when we build multi-tier applications we don't want to clutter all the beans in one config file [appname]-servlet.xml
. For example if you configure spring security
you wanted to include all those beans in security-context.xml
, in the same way all the beans belonging to service layer are configured in applicationContext.xml
and some would like to configure beans belonging to DAO layer in dao-context.xml
. So when you configure all these beans in different context files, you need to let know spring that these files exist as spring only knows about [appname]-servlet.xml
. ContextLoaderListener
will help spring recognize all the other context files.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With