1. 首先下载好JSON-RPC-JAVA压缩包;
里面包含jsonrpc-1.0.jar 和 jsonrpc.js;
jsonrpc-1.0.jar放在项目的WEB-INF/LIB下
jsonrpc.js 放到你要使用的页面引用;
2. 创建测试程序TestObject.java:
package com.gameframe;
public class TestObject {
public Integer sum(Integer a, Integer b) {
return a + b;
}
}
3. 当前页面引入
<%@ page import="com.gameframe.TestObject"%>
<script type="text/javascript" src="js/jsonrpc.js"></script>
<body>
<jsp:useBean id="JSONRPCBridge" scope="session"
class="com.metaparadigm.jsonrpc.JSONRPCBridge" />
<%TestObject t = new TestObject();JSONRPCBridge.registerObject("TestObject", t);%>
</body>
4. web.xml 配置里面加入
<!--servlet config for JSON-RPC-JAVA-->
<servlet>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<url-pattern>/JSON-RPC</url-pattern>
</servlet-mapping>
5.网页测试代码:
<form>
<input type="text" name="a" />
<input type="text" name="b" />
<input type="button" οnclick="fnSum(this.form)" value="Sum" />
</form>
6. javascript脚本函数添加
<script type="text/javascript">
function fnSum(form) {
try {
//Create a jsonrpc object for doing RPC.
jsonrpc = new JSONRpcClient("JSON-RPC");
// Call a Java method on the server
result1 = jsonrpc.TestObject.sum(form.a.value, form.b.value);
alert(result1);
} catch (e) {}
}
</script>
测试页面即可