1. First configure web. XML to add the servlet listening of the JSON-RPC:
<Servlet> <servlet-Name> jsonrpcservlet </servlet-Name> <servlet-class> jcore. jsonrpc. servlet. jsonrpcservlet </servlet-class> <load-on-startup> 2 </load-on-startup> </servlet> <servlet-mapping> <servlet-Name> jsonrpcservlet </ servlet-Name> <URL-pattern>/jrpc </url-pattern> </servlet-mapping>
NOTE: If sturts2 is used in the project, you must configure a filter to make the servlet take effect.
2. Add JSON-RPC.jar to project
3. Create a Java class that needs to be remotely called using JSON-RPC
Package jcore. jsonrpc. rpcobj; import Java. io. serializable; import Java. util. arraylist; import Java. util. date; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import jcore. jsonrpc. common. jsonrpcobject; public class mytestjsonrpc extends jsonrpcobject implements serializable {//Note: The jsonrpcobject class must be inherited and the serialization interface must be implemented.
Private list mylist = new arraylist (); Private map = new hashmap (); Public mytestjsonrpc () {mylist. add ("good"); // mylist. add (New testdomain (); // map can also be placed in the composite object map. put ("first", "first value"); map. put ("p2", new date (); // map. put ("Domain", mylist. get (1);}/*** return map object * @ return */public map getmap () {return map ;} /***** get a common object * @ return */public object getstr () {return mylist. get (0);}/*** get a composite object * @ return */public object getmyobj () {return mylist. get (1);}/**** get list object * @ return */public list getlist () {return mylist ;}}
4. Add the jsonrpcclient. js file to the project (this JS file is required for Web pages)
5. Foreground page using JSON-RPC Remote Call Java object
On the frontend page for remote callCodeAdd the following content:
5.1 register a Java object to be remotely called in JSP
<% Jcore. jsonrpc. Common. jsonrpcregister. registerobject (request, "mytestjsonrpc", jcore. jsonrpc. rpcobj. mytestjsonrpc. Class); %>
5.2 introduce JSON-RPC client JS and set project PATH variables
<SCRIPT charset = "UTF-8" type = "text/JavaScript"> var contextpath = "<% = PATH %> "; // key </SCRIPT> <SCRIPT charset = "UTF-8" type = "text/JavaScript" src = "<% = basepath %> jsonrpcclient. JS "> </SCRIPT>
Note: the PATH variable is defined in the JSP page header.
<% String Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %>
5.3 Remote Call
<SCRIPT charset = "UTF-8" type = "text/JavaScript"> // fngetrpc ("mytestjsonrpc"); var myrpc = RPC. mytestjsonrpc; var OBJ = myrpc. getstr (); alert (OBJ); </SCRIPT>