Springmvc source code interpretation of the Handlermapping-abstracturlhandlermapping series request distribution _java

Source: Internet
Author: User
Tags vars

abstracthandlermapping implementation of Handlermapping interface set GetHandler

1. Provide gethandlerinternal template method for subclass implementation

2. If no handler is obtained, the default defaulthandler is used

3. If handler is a string type, get the instance from the context

4. Add interceptor via Gethandlerexecutionchain package Handler

Abstracthandlermapping/** * Look up a handler for the given request, falling back to the default * handler if no spec
Ific one is found. * @param request Current HTTP request * @return The corresponding handler instance, or the default handler * @see #getHand Lerinternal * * Public final Handlerexecutionchain gethandler (HttpServletRequest request) throws Exception {Object handle
R = gethandlerinternal (request); if (handler = = null) {handler = Getdefaulthandler ();} if (handler = = null) {return null;}//Bean name or resolved Han
Dler? if (handler instanceof string) {string handlerName = (String) handler; handler = Getapplicationcontext (). Getbean (Handlern
AME);
Return Gethandlerexecutionchain (handler, request); 
}//abstracthandlermapping/** * Build a Handlerexecutionchain for the given handler including applicable. * <p>the default implementation simply builds a standard handlerexecutionchain with * the given handler R mapping ' s common interceptors, and any {@link mappedinterceptor}s * matching to the current request URL.
Subclasses may * Override the "in" to extend/rearrange the list of interceptors. * <p><b>NOTE:</b> The Passed-in handler object may a raw handler or a pre-built * Handlerexecutioncha In. This method should handle those two cases explicitly, * either building a new handlerexecutionchain or extending the exist
ing chain.  * <p>for simply adding an interceptor, consider calling {@code Super.gethandlerexecutionchain} * and invoking {@link
Handlerexecutionchain#addinterceptor} on the returned chain object. * @param handler The resolved handler instance (never {@code null}) * @param request current HTTP request * @return the Ha Ndlerexecutionchain (never {@code null}) * @see #getAdaptedInterceptors () * * * protected Handlerexecutionchain Gethandlerexecutionchain (Object handler, HttpServletRequest request) {Handlerexecutionchain chain = (Handler
instanceof Handlerexecutionchain)? (HandlerexEcutionchain) handler:new Handlerexecutionchain (handler);
Chain.addinterceptors (Getadaptedinterceptors ());
String Lookuppath = urlpathhelper.getlookuppathforrequest (request); for (Mappedinterceptor mappedinterceptor:mappedinterceptors) {if mappedinterceptor.matches (LookupPath, PathMatcher
)) {Chain.addinterceptor (Mappedinterceptor.getinterceptor ());}}
return chain; }

Take a look at the abstracturlhandlermapping implementation gethandlerinternal

Abstracturlhandlermapping/** * Look up a handler for the URL path of the given request.  * @param request Current HTTP request * @return The handler instance, or {@code null} if none found */@Override protected Object gethandlerinternal (HttpServletRequest request) throws Exception {//request to get URL String lookuppath = Geturlpath
Helper (). Getlookuppathforrequest (Request);
Find handler Object handler = Lookuphandler (Lookuppath, request) according to the URL; if (handler = null) {//If there is no match to handler need to find the default, the following needs to be cached Path_within_handler_mapping_attribute to request//We need to care fo
R the default handler directly, since we need to//expose the Path_within_handler_mapping_attribute for it as a.
Object rawhandler = null; 
if ("/". Equals (Lookuppath)) {Rawhandler = Getroothandler ();} if (Rawhandler = = null) {Rawhandler = Getdefaulthandler (); } if (Rawhandler!= null) {//Bean name or resolved handler? if (Rawhandler instanceof string) {string handlerName = (S
Tring) Rawhandler; Rawhandler = GetappliCationcontext (). Getbean (HandlerName);
}//Reserved checksum handler template method, no use of Validatehandler (Rawhandler, request);
Add the Expose property to the request's Interceptor handler = Buildpathexposinghandler (Rawhandler, Lookuppath, Lookuppath, NULL);
} if (handler!= null && logger.isdebugenabled ()) {Logger.debug ("Mapping [" + Lookuppath + "] to" + handler); else if (handler = = null && logger.istraceenabled ()) {logger.trace ("No handler mapping found for [" + Lookuppat
H + "]");
return handler;
}//abstracturlhandlermapping/** * Look up a handler instance for the given URL path. * <p>supports direct matches, e.g. a registered "/test" matches "/test", * and various ant-style pattern matches, E. G. A registered "/t*" matches * both "/test" and "/team".
For details, the Antpathmatcher class.
* <p>looks for the "most exact pattern, where most exact is defined as *" longest path pattern. * @param urlpath URL The bean is mapped to * @param request current HTTP request (to expose the path withIn the "Mapping to" * @return The associated handler instance, or {@code null} if not found * @see #exposePathWithinMapping * @see Org.springframework.util.AntPathMatcher */protected Object Lookuphandler (String URLPath, HttpServletRequest  Request) throws Exception {//Direct match? Find directly based on URL handler Object handler = This.handlerMap.get (URLPath); if (handler != null) {//Bean name or resolved handler? if (handler instanceof string) {string handlerName = (string) handler; hand
Ler = Getapplicationcontext (). Getbean (HandlerName);
} validatehandler (handler, request);
Return Buildpathexposinghandler (Handler, URLPath, URLPath, NULL); //Pattern match?
Through the expression of matching specific through the Antpathmatcher implementation, the specific following analysis list<string> matchingpatterns = new arraylist<string> ();
For (String RegisteredPattern:this.handlerMap.keySet ()) {if (Getpathmatcher (). Match (Registeredpattern, URLPath)) {
Matchingpatterns.add (Registeredpattern);
} String bestpatternmatch = null; Comparator<string> PatterncomparatoR = Getpathmatcher (). Getpatterncomparator (URLPath); if (!matchingpatterns.isempty ()) {Collections.sort (matchingpatterns, Patterncomparator); if (logger.isdebugenabled (
) {Logger.debug ("Matching Patterns for Request [" + URLPath + "] are" + matchingpatterns);}
The order ordinal number of the smallest priority Bestpatternmatch = Matchingpatterns.get (); } if (Bestpatternmatch!= null) {handler = This.handlerMap.get (bestpatternmatch);//Bean name or resolved handler? if (h Andler instanceof String) {string handlerName = (String) handler; handler = Getapplicationcontext (). Getbean (HandlerName)
;
} validatehandler (handler, request);
String pathwithinmapping = Getpathmatcher (). Extractpathwithinpattern (Bestpatternmatch, URLPath);
There might is multiple ' best patterns ', let's make sure we have the correct URI template variables//to all of them
map<string, string> uritemplatevariables = new linkedhashmap<string, string> (); for (String matchingpattern:matchingpatterns) {if patterncomparator.compare (bEstpatternmatch, matchingpattern) = =) {map<string, string> VARs = Getpathmatcher (). Extracturitemplatevariables (
Matchingpattern, URLPath);
map<string, string> decodedvars = Geturlpathhelper (). Decodepathvariables (Request, VARs);
Uritemplatevariables.putall (Decodedvars); } if (logger.isdebugenabled ()) {Logger.debug ("URI Template variables for request [" + URLPath +] are "+ Uritemplatev
Ariables);
Return Buildpathexposinghandler (Handler, Bestpatternmatch, pathwithinmapping, uritemplatevariables);
}//No handler found return null; }

Designed to validate handler, actually did nothing, including subclasses.

/**
* Validate The given handler against the current request.
* <p>the default implementation is empty. Can is overridden in subclasses,
* For example to enforce specific preconditions in URL expressed.
* @param handler the handler object to validate
* @param request current HTTP request
* @throws Exception if valid ation failed
*
/protected void Validatehandler (Object handler, HttpServletRequest request) throws Exception c9/>}

Encapsulates handler as Handlerexecutionchain and adds Pathexposinghandlerinterceptor and Uritemplatevariableshandlerinterceptor interceptors.

/** * Build a Handler object for the given raw handler, exposing the actual * handler, the {@link #PATH_WITHIN_HANDLER_MA
Pping_attribute}, as as the {@link #URI_TEMPLATE_VARIABLES_ATTRIBUTE} before executing the handler.  * <p>the default implementation builds a {@link handlerexecutionchain} * with a special interceptor that exposes the Path attribute and URI template variables * @param rawhandler The raw handler to expose * @param pathwithinmapping the PA  Th to expose before executing the handler * @param uritemplatevariables the URI template variables, can be {@code null} if No variables found * @return The final handler object/Protected object Buildpathexposinghandler (object Rawhandler, STR
ing Bestmatchingpattern, String pathwithinmapping, map<string, string> uritemplatevariables) {
Handlerexecutionchain chain = new Handlerexecutionchain (Rawhandler);
Chain.addinterceptor (New Pathexposinghandlerinterceptor (Bestmatchingpattern, pathwithinmapping)); if (! CollectionUtils.isempty (Uritemplatevariables)) {Chain.addinterceptor (New Uritemplatevariableshandlerinterceptor (
Uritemplatevariables));
return chain; }

The above content is small set to introduce the SPRINGMVC source code interpretation of the Handlermapping-abstracturlhandlermapping series of request distribution of relevant knowledge, hope to help everyone!

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.