Some time ago, I made a graduation project for one of my students, because I only needed JSP/servlet to implement it. I used to use the DWR framework, So I imitated the implementation of DWR:
It simply imitates the implementation of the dwr framework:
This is mydwrservlet. Java source code:
Package COM. xcy. core. web. DWR; import Java. io. bufferedreader; import Java. io. file; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstream; import Java. lang. reflect. method; import Java. lang. reflect. type; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import Java. util. map; import Java. util. set; import javax. servlet. servletexception; import javax. servl ET. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. XML. parsers. documentbuilder; import javax. XML. parsers. documentbuilderfactory; import javax. XML. parsers. parserconfigurationexception; import Org. w3C. dom. document; import Org. w3C. dom. element; import Org. w3C. dom. nodelist; import Org. XML. sax. saxexception;/*** @ author siuon ***/@ suppre Sswarnings ("all") public class mydwrservlet extends httpservlet {/*** serialversionuid */private final long serialversionuid = 1l; private final string RT = "\ r \ n "; private final string tab = "\ t"; private string context_path = NULL; private hashmap <string, jsclassmapping> jsandclassmapping = new hashmap <string, jsclassmapping> (); Private stringbuffer enginefilecontent; public mydwrservlet () {// system. out. Println ("mydwrservlet constructor");} @ overridepublic void Init () throws servletexception {documentbuilderfactory factory = documentbuilderfactory. newinstance (); documentbuilder builder = NULL; try {builder = factory. newdocumentbuilder (); document = builder. parse (new file (this. getservletcontext (). getrealpath ("/WEB-INF/mydwr. XML "); element root = document. getdocumentelement (); element allow = (Element) root. getelementsbytagname ("allow "). item (0); nodelist creates = allow. getelementsbytagname ("CREATE"); For (INT I = 0; I <creates. getlength (); I ++) {element create = (element) creates. item (I); string JavaScript = create. getattribute ("JavaScript"); string clazz = create. getattribute ("class"); Class C = Class. forname (clazz); jsandclassmapping. put (JavaScript, new jsclassmapping (JavaScript, C, C. new Instance ();} bufferedreader reader = new bufferedreader (New inputstreamreader (mydwrservlet. class. getresourceasstream ("engine. JS "); string line = NULL; enginefilecontent = new stringbuffer (); While (line = reader. readline ())! = NULL) {enginefilecontent. append (LINE + RT);} reader. close ();} catch (parserconfigurationexception e) {e. printstacktrace ();} catch (saxexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} catch (instantiationexception e) {e. printstacktrace ();} catch (illegalaccessexception e) {e. printstacktrace ();} catch (classnotfoundexception e) {e. printstacktrace () ;}@ overrideprotected Vo Id doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {context_path = req. getcontextpath () + "/mydwr/interface/"; string requesturi = req. getrequesturi (); If (! Requesturi. endswith (". JS ") return; string jsname = requesturi. substring (context_path.length (), requesturi. length ()-3); If ("engine ". equals (jsname) {write (resp, enginefilecontent. tostring (); return;} jsclassmapping = jsandclassmapping. get (jsname); If (jsclassmapping = NULL) return; try {If (jsclassmapping. getjsfilecontent () = NULL) {Class C = jsclassmapping. getclazz (); Type [] types = C. getgeneri Cinterfaces (); If (types. Length = 0) {Throw new runtimeexception (C. getclass () + "must implement an interface! ");} Class intface = (class) types [0]; method [] Methods = intface. getdeclaredmethods (); stringbuffer jsfilecontent = new stringbuffer ("Var mydwr = NULL;" + RT); jsfilecontent. append ("If (mydwr = NULL) {mydwr = new mydwr () ;};" + RT); jsfilecontent. append ("Var" + jsname + "= NULL;" + RT); jsfilecontent. append ("If (null =" + jsname + ") {" + jsname + "={};" + RT); stringbuffer functionbody = new stringbuffer (); for (INT I = 0; I <Methods. length; I ++) {functionbody. setlength (0); Method method = methods [I]; functionbody. append (jsname + ". "+ methods [I]. getname () + "= function ("); Class [] Params = method. getparametertypes (); stringbuffer paramarraystr = new stringbuffer ("["); For (Int J = 0; j <Params. length; j ++) {If (j = 0) {functionbody. append ("p" + J); paramarraystr. append ("p" + J);} else {functionbody. append (", P" + J); paramarraystr. append (", P" + J) ;}} paramarraystr. append ("];"); If (Params. length! = 0) {functionbody. append (",");} functionbody. append ("Callback) {" + RT); functionbody. append (Tab + "Var Params =" + paramarraystr + RT); functionbody. append (Tab + "mydwr. request ('"+ context_path +"', '"+ jsname +"', '"+ method. getname () + "', Params, callback);" + RT); functionbody. append ("}" + RT); jsfilecontent. append (functionbody);} jsclassmapping. setjsfilecontent (jsfilecontent) ;}} catch (securityexception e) {e. printstacktrac E ();} finally {If (jsclassmapping. getjsfilecontent ()! = NULL) {write (resp, jsclassmapping. getjsfilecontent (). tostring () ;}}@ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {req. setcharacterencoding ("UTF-8"); Map <string, Object> Params = (Map <string, Object>) req. getparametermap (); List <string> paramvalues = new arraylist <string> (); For (INT I = 0; I <Params. size (); I ++) {paramvalues. add (req. Getparameter ("p" + I);} string clazzandmethod = Req. getrequesturi (). substring (context_path.length (); string classname = clazzandmethod. Split ("! ") [0]; string methodname = clazzandmethod. Split ("! ") [1]; jsclassmapping = jsandclassmapping. get (classname); method [] Methods = jsclassmapping. getclazz (). getdeclaredmethods (); Method method = NULL; For (INT I = 0; I <methods. length; I ++) {If (methods [I]. getname (). equals (methodname) {method = methods [I]; break;} class [] types = method. getparametertypes (); object [] values = new object [paramvalues. size ()]; for (INT I = 0; I <types. length; I + +) {If ("integer ". equals (types [I]. getsimplename () {values [I] = integer. parseint (paramvalues. get (I);} else if ("double ". equals (types [I]. getsimplename () {values [I] = double. parsedouble (paramvalues. get (I);} else {values [I] = paramvalues. get (I); // other types when string processing .}} object result = NULL; try {result = method. invoke (jsclassmapping. getobjct (), values);} catch (exception e) {result = E. getmessage (); E. printstac Ktrace () ;} processresult (resp, result) ;}/ *** process the result after the method is called and process the returned values of different types separately. * @ Param resp * @ Param result * @ throws ioexception */private void processresult (httpservletresponse resp, object result) throws ioexception {stringbuffer temp = new stringbuffer ("["); if (result instanceof object []) {object [] objs = (object []) result; For (INT I = 0; I <objs. length; I ++) {temp. append ("'" + objs [I] + "'"); if (I! = Objs. length-1) {temp. append (",") ;}} temp. append ("]"); Result = temp. tostring ();} else if (result instanceof list) {list = (list) result; For (INT I = 0; I <list. size (); I ++) {object El = List. get (I); If (El instanceof map) {temp. append ("{"); map = (MAP) El; set <map. entry <object, Object> sets = map. entryset (); For (map. entry <object, Object> entry: sets) {object value = entry. getvalue () = NULL? "": Entry. getvalue (); temp. append ("'" + entry. getkey () + "':'" + value + "',");} temp. replace (temp. length ()-1, temp. length (), "}");} else {temp. append ("'" + list. get (I) + "'");} if (I! = List. size ()-1) {temp. append (",") ;}} result = temp. append ("]");} else if (result instanceof map) {temp = new stringbuffer ("{"); map = (MAP) result; set <map. entry <object, Object> sets = map. entryset (); For (map. entry <object, Object> entry: sets) {object value = entry. getvalue () = NULL? "": Entry. getvalue (); temp. append ("'" + entry. getkey () + "':'" + value + "',");} temp. replace (temp. length ()-1, temp. length (), "}"); Result = temp. tostring ();} else {// other types are used as stringresult = "'" + Result + "'";} write (resp, result. tostring ();} private void write (httpservletresponse resp, string content) throws ioexception {outputstream OS = resp. getoutputstream (); OS. write (content. getbytes ("UTF-8"); OS. flush (); OS. close ();}}
Engine. js
Function mydwr () {} mydwr. prototype. request = function (context, classname, methodname, Params, callback) {var querycontent = ""; if (Params. length) {for (VAR I = 0; I <Params. length; I ++) {if (I = 0) {querycontent + = "p" + I + "=" + Params [I];} else {querycontent + = "& P" + I + "=" + Params [I] ;}} var XMLHttpRequest; // generate the Ajax engine if (window. XMLHttpRequest) {// Mozilla XMLHttpRequest = new XMLHttpRequest ();} else if (window. activexobject) {// IE browser try {XMLHttpRequest = new activexobject ("msxml2.xmlhttp");} catch (e) {try {XMLHttpRequest = new activexobject ("Microsoft. XMLHTTP ");} catch (e) {}} XMLHttpRequest. open ("Post", context + classname + "! "+ Methodname, true); XMLHttpRequest. onreadystatechange = function () {If (XMLHttpRequest. readystate = 4) {// judge the object state if (XMLHttpRequest. status = 200) {// information has been returned successfully, start processing information // prompt ("DWR return:", XMLHttpRequest. responsetext); var datas = undefined; try {eval ("datas =" + XMLHttpRequest. responsetext + ";");} catch (e) {alert ("DWR error:" + E. message); datas ={};} callback. success (datas);} else {// The page is not normal eval ("Var datas =" + XMLHttpRequest. responsetext + ";"); callback. errorhandler (datas) ;}}; XMLHttpRequest. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); XMLHttpRequest. send (querycontent);} mydwr. prototype. hello = function () {alert ("Hello mydwr ");}
Source code:
Download mydwr source code