公司框架中集成了jsonrpc框架,所以研究了一下,下面是在讲解公司框架的时候写的一个关于jsonrpc使用流程的一个简单例子
使用步骤
<!--begin json rpc -->
<servlet>
<servlet-name>JSONRPCServlet</servlet-name>
<servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONRPCServlet</servlet-name>
<url-pattern>/JSON-RPC</url-pattern>
</servlet-mapping>
<!--end json rpc -->
<jsp:useBean id="JsonRpcTest" scope="session" class="com.wzk.jsonrpctest.JsonRpcTest" />
<%
JSONRPCBridge.registerObject("JsonRpcTest",JsonRpcTest);
%>
{
jsonrpc = new JSONRpcClient("../JSON-RPC");
}
工程目录结构如下图
<%
String path = request.getContextPath();
%>
<jsp:useBean id="JSONRPCBridge" scope="session" class="com.metaparadigm.jsonrpc.JSONRPCBridge"/>
<jsp:useBean id="JsonRpcTest" scope="session" class="com.wzk.jsonrpctest.JsonRpcTest" />
<%
JSONRPCBridge.registerObject("JsonRpcTest",JsonRpcTest);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="<%=path%>/script/jsonrpc.js"></script>
<script type="text/javascript" src="<%=path%>/script/jsonrpctest.js"></script>
</head>
<body onLoad="onLoad()">
<input type="text" value="milk" id="who" width="200" />
<input type="button" name="btn" value="返回字符" οnclick="textbtnclick('milk')"/>
<hr/>
<input type="button" name="btn" value="返回数组" οnclick="arraybtnclick()"/>
<hr/>
<input type="button" name="btn" value="测试传递数组" οnclick="testArrayArg()"/>
</body>
</html>
2,创建的jsonrpctest.js
function onLoad()
{
jsonrpc = new JSONRpcClient("../JSON-RPC");
}
function textbtnclick()
{
var name = document.getElementById("who").value;
var result = jsonrpc.JsonRpcTest.returnText(name);
alert(result);
}
function arraybtnclick()
{
var result = jsonrpc.JsonRpcTest.returnArray();
alert("数组长度="+result.length+" 数组内容 ="+result);
}
function testArrayArg()
{
var array = ["a","b"];
var result = jsonrpc.JsonRpcTest.testArrayArg(array);
alert("传递的参数数组长度="+result);
}
3,创建的java类,JsonRpcTest
package com.wzk.jsonrpctest;
import java.io.Serializable;
public class JsonRpcTest implements Serializable {
private final static long serialVersionUID = 1;
public String returnText(String name) {
return "Hello " + name;
}
public String[] returnArray() {
String temp[] = { "1", "2" };
return temp;
}
public int testArrayArg(String[] arg) {
return arg.length;
}
}
4,配置servlet
<!--begin json rpc -->
<servlet>
<servlet-name>JSONRPCServlet</servlet-name>
<servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONRPCServlet</servlet-name>
<url-pattern>/JSON-RPC</url-pattern>
</servlet-mapping>
<!--end json rpc -->