Spring mvc:handlermapping

Source: Internet
Author: User

Handlermapping

First, this is an interface, which is extensible. Its function is to match the corresponding handler according to different requests, which is to match a request processor according to the request . This process takes two steps: The first step is to register the handler with Handlermapping, and in the second step, the analysis request matches the rule from the registered handler to the corresponding handler, the controller. By default, SPRINGMVC gives us several implementations of the default handlermapping, which determine the order of execution by priority order.

Handlermapping Execution Order

In a spring MVC-based Web application, we can provide Dispatcherservlet with multiple handler-mapping for its use. Dispatcherservlet in the process of selecting handlermapping, it will sort according to the priority of the series of handlermapping we specify, and then prioritize the previous handlermapping. If the current handlermapping is able to return to the available Handler,dispatcherservlet, the Web request is processed using the currently returned handler, instead of continuing to ask for additional handlermapping. Otherwise, Dispatcherservlet will continue to ask for the priority of each handlermapping until an available handler is obtained.

Simpleurlhandlermapping

Now, with this implementation class, let's look at how handlermapping is registering and getting handler.

 Public classSimpleurlhandlermappingextendsabstracturlhandlermapping {Private Finalmap<string, object> UrlMap =NewHashmap<string, object>(); //configuring URLs to Bean name mappings via properties     Public voidsetmappings (Properties mappings) {Collectionutils.mergepropertiesintomap (mappings, This. UrlMap); }        //Configure URL-to-bean mappings     Public voidSeturlmap (map<string,?>UrlMap) {           This. Urlmap.putall (UrlMap); }         PublicMap<string,?>Geturlmap () {return  This. UrlMap; } @Override Public voidInitapplicationcontext ()throwsbeansexception {Super. Initapplicationcontext (); //registering the processor when initializingRegisterhandlers ( This. UrlMap); }        protected voidRegisterhandlers (map<string, object> UrlMap)throwsbeansexception {//if the configured processor map is empty, the warning        if(Urlmap.isempty ()) {Logger.warn ("Neither ' urlmap ' nor ' mappings ' Set on Simpleurlhandlermapping"); }          Else {              //for a URL-to-processor mapping that does not have a configuration, if the URL does not start with a slash (/), the append slash begins, and the processor is registered             for(Map.entry<string, object>Entry:urlMap.entrySet ()) {String URL=Entry.getkey (); Object Handler=Entry.getvalue (); //prepend with Slash if not already present.                 if(!url.startswith ("/") ) {URL= "/" +URL; }                  //Remove whitespace from handler bean name.                 if(HandlerinstanceofString) {Handler=(String) handler). Trim ();              } registerhandler (URL, handler); }          }      }    }  

First, it stores the correspondence between the request and the controller through a hashmap, which is to save the registration information. The classes are managed by the IOC container manager, handlermapping, and the corresponding relationship. Where key is the path information for the HTTP request, value can be a string, or a handlerexecutionchain that handles the request, and if it is a string type, it will be treated as the bean name of spring. In the creation of the Handlermapping object, the IOC container executes a container callback method Setapplicationcontext, in which the Initapplicationcontext method is called to initialize, Each subclass can overwrite this method according to the different requirements. The registration of HANDLERMAP information is executed in the Initapplicationcontext method.
The method of obtaining handler in his parent class, the source code is as follows:

protectedObject gethandlerinternal (HttpServletRequest request)throwsException {String Lookuppath= This. Urlpathhelper.getlookuppathforrequest (Request); //find the handler that match the matching rule. The possible result is a Handlerexecutionchain object or nullObject handler =Lookuphandler (Lookuppath, request); //If no matching handler are found, you need to handle the next default handler    if(Handler = =NULL) {          //we need to care for the default handler directly, since we need to//expose the Path_within_handler_mapping_attribute for it as well. Object Rawhandler =NULL; if("/". Equals (Lookuppath)) {Rawhandler=Getroothandler (); }          if(Rawhandler = =NULL) {Rawhandler=Getdefaulthandler (); }                      //In the Getroothandler and Getdefaulthandler methods, it is possible to hold the bean name.         if(Rawhandler! =NULL) {              //Bean name or resolved handler?             if(RawhandlerinstanceofString) {String HandlerName=(String) Rawhandler; Rawhandler=Getapplicationcontext (). Getbean (HandlerName);              } validatehandler (Rawhandler, request); Handler= Buildpathexposinghandler (Rawhandler, Lookuppath, Lookuppath,NULL); }      }              //If handler is still empty, an error is thrown.     if(Handler! =NULL&& This. mappedinterceptors! =NULL) {Set<HandlerInterceptor> mappedinterceptors = This. Mappedinterceptors.getinterceptors (Lookuppath, This. Pathmatcher); if(!Mappedinterceptors.isempty ())              {Handlerexecutionchain chain; if(HandlerinstanceofHandlerexecutionchain) {Chain=(Handlerexecutionchain) handler; } Else{chain=NewHandlerexecutionchain (handler); } chain.addinterceptors (Mappedinterceptors.toarray (Newhandlerinterceptor[mappedinterceptors.size ()]); }      }      if(Handler! =NULL&&logger.isdebugenabled ()) {Logger.debug ("Mapping [" + Lookuppath + "] to handler ' + handler +" ' "); }      Else if(Handler = =NULL&&logger.istraceenabled ()) {Logger.trace ("No handler mapping found for [" + Lookuppath + "]"); }      returnhandler; } 

Interface definition

Once we've seen this, we'll look back at the definition of the Handleramapping interface:

 Public Interfacehandlermapping {String Path_within_handler_mapping_attribute= handlermapping.class. GetName () + ". Pathwithinhandlermapping"; String Best_matching_pattern_attribute= handlermapping.class. GetName () + ". Bestmatchingpattern"; String introspect_type_level_mapping= handlermapping.class. GetName () + ". Introspecttypelevelmapping"; String Uri_template_variables_attribute= handlermapping.class. GetName () + ". Uritemplatevariables"; String Producible_media_types_attribute= handlermapping.class. GetName () + ". Produciblemediatypes";  Public AbstractHandlerexecutionchain GetHandler (HttpServletRequest request)throwsException;}

Sharp-eyed's classmates may have to say, this interface to get handler method how the return value is Handlerexecutionchain instead of a handler? Handlerexecutionchain This class, from the name can be intuitively seen, this object is an execution chain of encapsulation. Familiar with the Struts2 know that the action object is also a layer of interceptor packaging, here can make an analogy, that SPRINGMVC is really absorbed Struts2 part of the design ideas. We can look at the source code, too long I will not post. From the source code can be seen, a real object of execution, there is a bunch of interceptors. This is not the implementation of STRUTS2, SPRINGMVC no suspicion, or the use of this package. After getting handlerexecutionchain This execution chain (execution chain), the next process will be expanded around it. At this point, the entire execution of the Handlerexecutionchain is clear: before actually invoking its handler object, an array of Handlerinterceptor interface implementation classes will be traversed, and the Prehandle method will be called sequentially. Then the real handler object will be called.
Summary : The main content here is the registration and acquisition of the two processes, as well as SPRINGMVC to handler some of the package. Seriously read the source code, you can clearly see this class of the entire implementation process. To deepen the understanding of the SPRINGMVC implementation process, the feeling is quite good.

Reference

http://blog.csdn.net/zhuojiajin/article/details/46292125

Spring mvc:handlermapping

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.