I am new to Spring MVC. I have a web application. I have the following configuration:
<welcome-file-list>
<welcome-file>list.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Do I need to add the following line to the web.xml file?
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).
Whereas DispatcherServlet is expected to load beans containing web components such as controllers, view resolvers, and handler mappings, ContextLoaderListener is expected to load the other beans in your application.
As per my understanding, ContextLoaderListener reads the Spring configuration file (with value given against contextConfigLocation in web. xml), parses it and loads the singleton bean defined in that config file. Similarly when we want to load prototype bean, we will use same webapplication context to load it.
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web. xml and use a contextConfigLocation to set which context files to load. You can then use the WebApplicationContext to get a handle on your beans.
Yes you need to add ContextLoaderListener
in web.xml
,
only if you want to load other Spring context xml files as well while loading the app
and you can specify them as
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
Only if you have two config xml files. One with Services / DAOs and another with Controller. If you have configured everything in one spring config file you don't need the ContextLoaderListener
, just the dispatcher servlet is sufficient.
It is recommended to split the config into two and use the ContextLoaderListener
to create the root application context and the dispatcher servlet to create the web layer application context.
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