Dreamvc Framework (iii), what did Dispartcher do?

Source: Internet
Author: User

In this article I will introduce some of the DREAMVC core class dispatcher have done something, first we first look at the Init method, which is in Dispatcherservlet and Dispatcherfilter will be called a method

void init (Fixableconfig config) throws Servletexception{this.servletcontext=config.getservletcontext (); try { Initproxy (config); Log.info ("Init controllers and Control");} catch (Servletexception e) {throw e;} catch (Exception e) {throw new Servletexception ("Dispatcher Init failed.", e);}}
/** * controller/interceptor/* @param config context * @throws Exception */private void initproxy (fixableconfig config) t Hrows Exception {String iocname=config.getinitparameter ("container"), if (iocname==null| | "". Equals (Iocname)) {throw new Noparamterexception ("Missing init parameter <container>.");} /* Codeenhancement=config.getinitparameter ("codeenhancement"); if (codeenhancement==null| | Codeenhancement.equals ("")) {throw new Noparamterexception ("Missing init parameter <codeenhancement>."); if (! Codeenhancement.equals ("Springasm") &! Codeenhancement.equals ("Javassist")) {throw new Noparamterexception ("You must get a right codeenhancement handler like Springasm If your IOC is Spring ");} */iocfactory factory=factoryhelper.getinstance (). Createiocfactory (Iocname); Factory.init (ServletContext); List<object> controllerbean=factory.getcontrollers (); List<object> interceptorbeans=factory.getinterceptors ();//controller/interceptorinitcontrollerhander ( Controllerbean); initinterceptOrhander (Interceptorbeans); Inittemplates (config);} 
In Initproxy this method, first we get the IOC module, after initialization, the controller and the interceptor set, then the operation and initialization of the template, first look at Initcontrollerhander

private void Initcontrollerhander (list<object> controllerbean) {log.info ("handler controller init"); int size= Controllerbean.size (); for (int i = 0; i < size; i++) {Object obj=controllerbean.get (i); Addurlmather (obj);}}
private void Addurlmather (Object obj) {Class clazz=obj.getclass (); Method[] Method=clazz.getmethods (); for (int i = 0; i < method.length; i++) {if (Islegalmethod (Method[i])) {String Annota Tion=method[i].getannotation (Requesturi.class). Value (); Action action=new Action (obj, Method[i]); Uri uri=new uri (annotation); Uri_action.put (URI, action); }}}
/** * * @param Method * @return */private Boolean Islegalmethod (Method method) {RequestUri requesturi=method.getannotation ( Requesturi.class); if (requesturi==null| | Requesturi.value (). Length () ==0) {return false;} if (Modifier.isstatic (Method.getmodifiers ())) {return false;} Class<?>[] Putparameters=method.getparametertypes (); for (class<?> class1:putparameters) {if (! Switcherfactory.islegalmethod (Class1)) {return false;}}     class<?> RetType = Method.getreturntype (); if (rettype.equals (void.class) | | | rettype.equals (string.class) | |     Renderer.class.isAssignableFrom (RetType)) {return true;     }else{Log.warn ("Your method named" +method.getname () + "' s result type must be String/void/templement"); }return false;} 
We first have to get this controller inside the corresponding method, and then the method to check, key words, return values, parameters, and so on, switcher package inside the definition of some of the parameters of the processing, mainly on the parameters of the inspection, readers can view their own, Then we get the annotation annotation, the request path to the method, which is associated to the URI class,

Package Org.majorxie.dreamvc.tag;import Java.util.arraylist;import Java.util.list;import java.util.Map;import org.majorxie.dreamvc.interceptor.interceptor;/** * URI class * @author Xiezhaodong * */public class URI {private String Uri;pu Blic String GetURI () {return URI;} public void Seturi (String uri) {This.uri = URI;} Public URI (String URI) {super (); This.uri = URI;} /** * matches the corresponding Interceptor * @param interceptor_map with Interceptor map * @return The Interceptor chain of the request path */public list<interceptor> g Etmatchedinterceptor (map<string,interceptor> interceptor_map) {list<interceptor> list=new ArrayList <Interceptor> (); for (string InterceptorUri:interceptor_map.keySet ()) {string Returninterceptor=matcher ( This.uri, Interceptoruri); if (returninterceptor!=null) {List.add (Interceptor_map.get (Returninterceptor));}} return list;} /** * Determine if the URL and the interceptor path are relatively equivalent, such as/user/login and/user/* are relatively equivalent, can match * @param URL request URL * @param interceptors interceptor URL * @return Match successfully returned , otherwise returns null */public string Matcher (string url,string InterCeptors) {if (Url.equals (interceptors)) return interceptors;//exactly the same if (Interceptors.endswith ("/")) return null;// Cannot end like this string[] urlsarray=url.split ("/"); String[] Interceptorsarray=interceptors.split ("/"); if (Interceptorsarray.length<urlsarray.length) {Boolean Ismatched=true;if (Interceptorsarray[interceptorsarray.length-1].equals ("*")) {//if shorter than his URL must end with a * end for (int i = 0; i < Interceptorsarray.length; i++) {if (!ismatched (Urlsarray[i], interceptorsarray[i]) {//with a short one for traversal Ismatched=false;break;}} if (ismatched) return interceptors;} Else{return null;}} if (interceptorsarray.length==urlsarray.length) {//equals Boolean ismatched=true;for (int i = 0; i < Interceptorsarray.length; i++) {//length are the same if (!ismatched (Urlsarray[i], interceptorsarray[i]) {ismatched=false;break;}} if (ismatched) {//If the last match is complete or the same, return interceptors;}} return null;} /** * matches each node * @param urlpart Original path node * @param interspart Intercept path node * @return */private boolean ismatched (String urlpart,str ing Interceptorpart) {return urlpart.equals (Interceptorpart) ||interceptorpart.equals ("*");} Override Hashcode () and the Equals method to use as map Key@overridepublic int hashcode () {//TODO auto-generated method Stubreturn Uri.hashcode ();} @Overridepublic boolean equals (Object obj) {if (this==obj) {return true;} else if (obj instanceof URI) {return ((URI) obj). Uri.equals (This.uri);} return false;}}
Inside this class, there are some operations that encapsulate the URI request, match the Interceptor, and so on, overwriting the hashcode () and Equals () functions as key HashMap. Next is the action class, which has 3 parameters

Private Object instance;private Method method;private class<?>[] arguments;
Encapsulates the method, the class, and the parameter

Finally, we put the URI and action as map key,value into the map! Next load the Interceptor class

private void Initinterceptorhander (list<object> interceptorbeans) {int size=interceptorbeans.size (); for (int i = 0; I <size; i++) {Interceptor interceptor= (Interceptor) Interceptorbeans.get (i); Interceptoruri interceptoruri= Interceptor.getclass (). Getannotation (Interceptoruri.class); String Annotationuri=interceptoruri.url (); Interceptor_uri.put (Annotationuri, Interceptor);}}
Most always associate URIs with interceptor.

Finally load the template we need to use

private void Inittemplates (Fixableconfig config) throws exception{string template=config.getinitparameter ("template" ); if ("". Equals (template) | | Template==null) {Log.info ("You don't have template Parameters, we'll user default JSP template"); template=jsptemplate;} Templatefactory templatefactory=factoryhelper.getinstance (). createtemplatefactory (template); Templatefactory.init (config); templatefactory.setinstance (templatefactory);}


Similar to loading IOC containers, DREAMVC automatically selects JSP templates if no template is specified



In this way, the initialization of the dispatcher class is done. Next, we'll show you how a request will go to the relevant method, the injection of parameters, how the interceptor works, and how the Interceptor ur is matched.

Reprint please specify the source http://blog.csdn.net/a837199685









Dreamvc Framework (iii), what did Dispartcher do?

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.