Spring can also load a spring context configuration file in Dispatcherservlet by configuring Contextloaderlistener in Web. XML to load the context configuration file, so what's the difference between the two?
When the context loaded in Contextloaderlistener is successful, spring stores applicationcontext in ServletContext with a key value of " Org.springframework.web.context.WebApplicationContext.ROOT "in the attribute.
this. context);
Available through Webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext) or Webapplicationcontextutils.getwebapplicationcontext (ServletContext) method to obtain the corresponding applicationcontext.
Dispatcherservlet if the value of the Publishcontext property is set to True after the context of the load has been successfully (true by default) The applicationcontext will be stored in the attribute of Org.springframework.web.servlet.FrameworkServlet.CONTEXT. + (Servletname).
For example, Web. XML is configured as follows:
<servlet> <Servlet-name>Mvcservlet</Servlet-name> <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class> <Init-param> <Param-name>Contextconfiglocation</Param-name> <Param-value>Classpath*:/spring/config/applicationcontextmvc.xml</Param-value> </Init-param> <Load-on-startup>1</Load-on-startup> </servlet>
The attribute key value for the corresponding ApplicationContext is Org.springframework.web.servlet.FrameworkServlet.CONTEXT.mvcServlet.
Dispatcherservlet will store this applicationcontext in request with the attribute value of In Org.springframework.web.servlet.DispatcherServlet.CONTEXT:
Request.setattribute (Web_application_context_attribute,getwebapplicationcontext ());
can be obtained by requestcontextutils.getwebapplicationcontext or Webapplicationcontextutils.getwebapplicationcontext ( Servletcontext,attrname) method to obtain the corresponding applicationcontext.
As can be seen from the above analysis, the ApplicationContext loaded by Dispatcherservlet can be considered a private context of MVC, Because the key value stored in ServletContext is not the same as the key value that is used by the ApplicationContext loaded through Contextloaderlistener, So if you only use Dispatcherservlet to load the context, if there are places in the program that use Webapplicationcontextutils.getrequiredwebapplicationcontext ( ServletContext) to try to get applicationcontext, it throws "No Webapplicationcontext found:no contextloaderlistener registered?" The exception.
The difference between the Contextloaderlistener and the ApplicationContext loaded by Dispatcherservlet