Spring Learning Summary (2.3)-spring mvc:handlermapping

Source: Internet
Author: User

The previous blog tells the Dispathcerservlet of the process and how it works, starting with this blog and going deep into Dispatcherservlet's interior to see several of its main components. Then this article begins with the handlermapping component.
handlermappingFirst, 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 OrderIn 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.
simpleurlhandlermappingnow, with this implementation class, let's look at how handlermapping is registering and getting handler.
public class Simpleurlhandlermapping extends abstracturlhandlermapping {private final map<string, object>        UrlMap = new hashmap<string, object> (); Mapping public void Setmappings (properties mappings) {Collectionutils.mergepropertiesintomap) through the property configuration URL to the bean name (      mappings, This.urlmap);      }//configure URL to bean mapping public void Seturlmap (map<string,?> urlmap) {this.urlMap.putAll (URLMAP);      } public map<string,?> Geturlmap () {return this.urlmap; } @Override public void Initapplicationcontext () throws Beansexception {Super.initapplicationcontext          ();      When initializing, register processor registerhandlers (THIS.URLMAP); } protected void Registerhandlers (map<string, object> urlmap) throws Beansexception {//If the configured processor is mapped to NULL, then warning if (Urlmap.isempty ()) {Logger.warn ("neither ' urlmap ' nor ' mappings ' set on Simpleurlhandlerma          Pping ");     }     else {//For a URL-to-processor mapping that does not have a configuration, if the URL does not begin with a slash (/), then the append slash begins, registering the processor for (map.entry<string, OBJEC                  T> 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 (handler instanceof String) {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:
Protected Object gethandlerinternal (HttpServletRequest request) throws Exception {String Lookuppath = this.urlpathhe              Lper.getlookuppathforrequest (Request); Find the handler that match the matching rule.              Possible results are Handlerexecutionchain objects or null Object handler = Lookuphandler (Lookuppath, request); If no matching handler is found, you need to handle the next default handler if (handler = = null) {//We need to care for the default handler D          irectly, 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 (Rawhandler instanceof string) {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
Interface DefinitionOnce we've seen this, we'll look back at the definition of the Handleramapping interface:
Public interface Handlermapping {     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 abstract Handlerexecutionchain GetHandler (HttpServletRequest request) throws Exception; }

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.

Spring Learning Summary (2.3)-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.