In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to carry out SpringMVC DispatcherServlet source code analysis, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.
DispatcherServlet source code analysis
The core of SpringMVC is DispatcherServlet, and all requests are forwarded to DispatcherServlet, and then the specific control layer (Handler) is executed through DispatcherServlet to return ModelAndView to the client view for display.
/ / 3. Inject our DispatcherServlet into the serlvet container ServletRegistration.Dynamic dynamic = servletContext.addServlet ("dispatcher", new DispatcherServlet (app)); / / 4. Fill in the url path mapping dynamic.addMapping ("/")
DispatcherServlet is actually a Servlet class, nothing more than a wrapper layer, through url can be mapped to find the request method defined in our SpringMvc.
Source code analysis:
Class integration relationship
DispatcherServlet inherits FrameworkServlet inherits HttpServlet
Facing the basic idea of rewriting the first parent class, in the subclass.
Get the answer: let's see if HttpServlet finds our last subclass.
Protected final void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.processRequest (request, response);}
The relationship between DispatcherServlet and Servlet
Relationship: DispatcherServlet inherits FrameworkServlet inherits HttpServlet
Process execution relationship:
HttpServlet service method to determine the type of request method
FrameworkServlet doService
DispatcherServlet doService
Initialization of DispatcherServlet
Its init method is called during the initialization phase of servlet, so we first need to see if the init method is overridden in DispatcherServlet. We found this method in its parent class HttpServletBean
Public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware {.... Public final void init () throws ServletException {if (this.logger.isDebugEnabled ()) {this.logger.debug ("Initializing servlet'" + this.getServletName () + "'");} / / parse init-param and encapsulate it into pvs PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues (this.getServletConfig (), this.requiredProperties) If (! pvs.isEmpty ()) {try {/ / converts the current servlet class to a BeanWrapper, so that the value of init-param can be injected as Spring BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess (this); ResourceLoader resourceLoader = new ServletContextResourceLoader (this.getServletContext ()) / / register a custom attribute editor and parse bw.registerCustomEditor (Resource.class, new ResourceEditor (resourceLoader, this.getEnvironment ()) using ResourceEditor once encountered with attributes of type Resource; / / empty implementation, leaving subclasses to override this.initBeanWrapper (bw); / / attribute injection bw.setPropertyValues (pvs, true) } catch (BeansException var4) {if (this.logger.isErrorEnabled ()) {this.logger.error ("Failed to set bean properties on servlet'" + this.getServletName () + ", var4);} throw var4;}} / / for subclass extension this.initServletBean () If (this.logger.isDebugEnabled ()) {this.logger.debug ("Servlet'" + this.getServletName () + "'configured successfully");}}....}
The initialization process of DispatcherServlet is mainly by converting the current instance of Servlet type into an instance of BeanWrapper type, so that the corresponding attributes can be injected using the injection function provided in Spring.
Let's take a look at the initialization of servletBean. The parent class FrameworkServlet of HttpServletBean overrides its initServletBean function, as follows:
Protected final void initServletBean () throws ServletException {this.getServletContext (). Log ("Initializing Spring FrameworkServlet'" + this.getServletName () + "'"); if (this.logger.isInfoEnabled ()) {this.logger.info ("FrameworkServlet'" + this.getServletName () + ": initialization started");} / / timer, execution time of statistical initialization long startTime = System.currentTimeMillis () Try {/ / critical initialization logic is delegated to this method this.webApplicationContext = this.initWebApplicationContext (); / / designed to subclass override this.initFrameworkServlet ();} catch (RuntimeException | ServletException var5) {this.logger.error ("Context initialization failed", var5); throw var5;} if (this.logger.isInfoEnabled ()) {long elapsedTime = System.currentTimeMillis ()-startTime This.logger.info ("FrameworkServlet'" + this.getServletName () + "': initialization completed in" + elapsedTime + "ms");} initialization of WebApplicationContext
The main job of the initWebApplicationContext function is to create or refresh the WebApplicationContext instance and initialize the variables used by the servlet function.
Protected WebApplicationContext initWebApplicationContext () {WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext (this.getServletContext ()); WebApplicationContext wac = null; if (this.webApplicationContext! = null) {/ / context instance is injected into the constructor wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac If (! cwac.isActive ()) {if (cwac.getParent () = = null) {cwac.setParent (rootContext);} / refresh context this.configureAndRefreshWebApplicationContext (cwac) } if (wac = = null) {/ / load webApplicationContextwac = this.findWebApplicationContext () according to contextAttribute attribute;} if (wac = = null) {wac = this.createWebApplicationContext (rootContext);} if (! this.refreshEventReceived) {this.onRefresh (wac);} if (this.publishContext) {String attrName = this.getServletContextAttributeName () This.getServletContext () .setAttribute (attrName, wac); if (this.logger.isDebugEnabled ()) {this.logger.debug ("Published WebApplicationContext of servlet'" + this.getServletName () + "'as ServletContext attribute with name [" + attrName + "]");}} return wac;}
Refresh method onRefresh
Protected void onRefresh (ApplicationContext context) {this.initStrategies (context);}
Protected void initStrategies (ApplicationContext context) {
InitMultipartResolver (context); / / initialize the upload file parser (or multipart request parser)
InitLocaleResolver (context); / / initialize the localized parser
InitThemeResolver (context); / / initialize the theme parser
InitHandlerMappings (context); / / initialize the processor mapper
InitHandlerAdapters (context); / / initialize the processor adapter
InitHandlerExceptionResolvers (context); / / initialize the handler exception parser
InitRequestToViewNameTranslator (context); / / initialize request to view name translator
InitViewResolvers (context); / / initialize the view parser
InitFlashMapManager (context); / / initialize the redirect data manager
}
DispatcherServlet logic processing protected void doDispatch (HttpServletRequest request, HttpServletResponse response) throws Exception {... Try {try {. / / looks up the control layer class method through the url path address, and returns 404mappedHandler = this.getHandler (processedRequest) directly if the transformation is not found. HandlerAdapter ha = this.getHandlerAdapter (mappedHandler.getHandler ()); String method = request.getMethod (); boolean isGet = "GET" .equals (method); If (! mappedHandler.applyPreHandle (processedRequest, response)) {return;} mv = ha.handle (processedRequest, response, mappedHandler.getHandler ()); MappedHandler.applyPostHandle (processedRequest, response, mv);.} SpringMVC source code positioning Handler principle
Private List handlerMappings
MappedHandler = this.getHandler (processedRequest)
HandlerAdapter ha = this.getHandlerAdapter (mappedHandler.getHandler ())
If (! mappedHandler.applyPreHandle (processedRequest, response)) {return;}
/ * the request method is pre-intercepted. If true is returned, the target method (request method) will be executed. If false is returned, the target method will not be executed. * / @ Overridepublic boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String token = request.getParameter ("token"); System.out.println ("> token > > pageIndex"); / / execute after the request. } DispatcherServlet source code flow analysis
1. Execute doDispatch
two。 The method of calling the getHandler method to obtain the request target is the specific method of requesting the control layer corresponding to the url mapping path.
The role of handlerMappings is to find the location of the controller, such as xml and annotation mode.
3. Call getHandlerAdapter to get the control layer adapter RequestMappingHandlerAdapter
4. Execute the interceptor prefix method preHandle () if returned as true
5. Execute the actual request target method to return the modeAndView object
6. Execute the interceptor PostHandle () method
7. Set the content of the render view layer
8. Execute interceptor completion party
SpringMVC control layer container initialization
HttpServletBean init () method
FrameworkServlet initServletBean method → initWebApplicationContext ()
DispatcherServlet onRefresh method → initStrategies () method
Protected void onRefresh (ApplicationContext context) {this.initStrategies (context);}
Initialize when we initialize the servlet container
This.initHandlerMappings (context)
The above content is how to analyze the DispatcherServlet source code of SpringMVC. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.