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 this method of Initproxy. First we get the IOC module, and after initialization, we get the controller and interceptor collection at once. The operation and the initialization of the template are followed. 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 the corresponding method inside the controller, and then check the method. Keyword return value, number of parameters, and so on. Inside the switcher package, some of the processing of the parameters is defined. The main is to check the number of parameters. Readers can view them on their own. Then we get the annotation annotation, which is the request path to the method, which is associated with 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;} /** * Infer if the URL and interceptor path are relatively equivalent, for example,/user/login and/user/* are relatively equivalent. Match on line * @param URL request URL * @param interceptors interceptor URL * @return Match successfully returned, otherwise null */public string Matcher (String url,string i NtercEptors) {if (Url.equals (interceptors)) return interceptors;//completely 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 ("*")) {//assuming shorter than his URL last required to end with a * 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) {//Assuming that the final match is complete or the same word return interceptors;}} return null;} /** * matches each node * @param urlpart Original path node * @param interspart Intercept path node * @return */private boolean ismatched (String Urlpart,stri Ng 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. Overrides the Hashcode () and Equals () functions. As a key to HashMap. And then there's the action class, which has 3 parameters in the class.

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

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);}


Almost identical to loading the IOC container, assuming that no template is specified, DREAMVC will voluntarily select the JSP template



Such The initialization of the dispatcher class is done. Next, we'll show you how a request can be injected into the relevant method, the number of references, and how the interceptor works. and the Interceptor ur match way

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









Dreamvc Framework (iii), what did Dispartcher do?

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.