当前位置: 代码迷 >> JavaScript >> 本国人:JSON-RPC之初识
  详细解决方案

本国人:JSON-RPC之初识

热度:165   发布时间:2012-10-09 10:21:45.0
国人:JSON-RPC之初识
相关链接
1 json-rpc-for-java
http://code.google.com/p/json-rpc-for-java/downloads/list
2 国人的json-rpc-for-java比老外的更好用
http://blog.csdn.net/jxpath/archive/2009/11/27/4888260.aspx
使用之后发现这个框架:JSON-RPC要注意的三个地方,其它还有什么就没有试出来了呀
1 JavaBean对象要用默认的无参构造函数,必须实现 java.io.Serializable序列化接口
2 JS方面: 必须注意:你的参数是String类型请在前后加',如:{username:'张三'}, 如是空值后台也会报错!
在传递对象请确保:参数类型的正确性,如你在age年龄中输入了非数字后台将报错!
3 通过在web.xml中注册的方式不能用!

更多精彩请参见官方示例:有更强大的级联调用
一 环境:XP+Myeclipse6.6+Tomcat7+JDK1.6
二 项目目录结构如下图

1 UserJSON.java
package jcore.jsonrpc.rpcobj;
//必须是jcore.jsonrpc.rpcobj包下才可以免注册
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jcore.jsonrpc.common.JsonRpcObject;
import jcore.jsonrpc.entity.User;

public class UserJSON extends JsonRpcObject  implements java.io.Serializable{

	private static final long serialVersionUID = 1L;
	
	/**
	 * 直接返回普通类型
	 * */
	public String helloJSONPRC(String userName){
		//可从getAllInputParms获取页面值
		//String userName = (String)this.getAllInputParms().get("userName");	
		return "Hello World "+userName +" !";	
	}
	
	/***
	 * 返回JavaBean类型
	 * */
	public User getUser(){
		return new User(1,"张三","123456",25);
	}
	
	public String saveUser(User user){
		System.out.println("id: "+user.getUserId() + ",name:" + user.getUserName() + ",password: " + user.getUserPassword() + ",age: " + user.getAge());
		return "保存用户成功!";
	}
	
	
	/**
	 * 返回List集合
	 * */
	public List<User> getUserAll(){
		
     	List<User> users = new ArrayList<User>();
     	users.add(new User(1,"张三","123456",25));
     	users.add(new User(2,"李逵","123123",20));
     	return users; 		
	}
	
	/**
	 * 返回Map集合
	 * */
	public Map<String,User> getUserMapAll(){
		
     	Map<String,User> maps = new HashMap<String,User>();
     	maps.put("1",new User(1,"张三","123456",25));
     	maps.put("2",new User(2,"李逵","123123",20));
     	return maps; 		
	}
}

2 User.java
package jcore.jsonrpc.entity;

public class User implements java.io.Serializable{

	private static final long serialVersionUID = 1L;
	private int userId;
	private String userName ;
	private String userPassword;
	private int age ;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public User(int userId, String userName, String userPassword, int age) {
		super();
		this.userId = userId;
		this.userName = userName;
		this.userPassword = userPassword;
		this.age = age;
	}
	
	/**
	 * 必须注意:JSON-RPC必须要求你的JavaBean对象要用默认的无参构造函数
	 * */
	public User(){
		
	}
}

3 web.xml
<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>

3 index.jsp
<%@ page language="java"  pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>JSON-RPC</title>
	<script type="text/javascript">
     var contextPath = "<%=path%>";// 关键的地方
   </script>
   <script type="text/javascript" charset="UTF-8" src="js/JsonRpcClient.js"></script>
	<script type="text/javascript">
	  var myrpc = rpc.UserJSON;	
	  /**
	  传递变通字符串
	  */
	  function helloName(){	 
	    var userName = document.getElementById("userName").value;
	  	alert(myrpc.helloJSONPRC(userName));
	  }
	  
	  /**
	  传递javaBean对象
	  */
	  function saveUser(){
	    /**
	    必须注意:你的参数是String类型请在前后加',如:{username:'张三'}
	    如是空值后台也会报错!!
	    在传递对象请确保:参数类型的正确性,如你在age年龄中输入了非数字后台将报错!
	    */
	  	var user = "{";
	  	user += "userId:"+ document.getElementById("userId").value;
	  	user += ",userName:'"+document.getElementById("userName").value+"'";
	  	user += ",userPassword:'"+document.getElementById("userPassword").value+"'";
	  	user += ",age:"+document.getElementById("age").value;
	  	user += "}";
	  	var message = myrpc.saveUser(user);
	  	alert(message);	  	
	  }
	  
	  /**
	  获取对象
	  */
	  function getUser(){
	    var user = myrpc.getUser();
	  	document.getElementById("userId").value = user.userId;
	  	document.getElementById("userName").value = user.userName;
	  	document.getElementById("userPassword").value = user.userPassword;
	  	document.getElementById("age").value = user.age;
	  }
	  
	  /**
	  获取集合对象
	  */
	  function listUser(){
	  	var users = myrpc.getUserAll();
	  	var size = users.length;
	  	var userInfo = "<table border='1'>";
	  	userInfo += "<tr>";
  		userInfo += "<td>ID</td>";
  		userInfo += "<td>姓名</td>";
  		userInfo += "<td>密码</td>";
  		userInfo += "<td>年龄</td>";
  		userInfo += "</tr>";
	  	var user = '';
	  	for(var i =0;i<size;i++){
	  	    user = users[i];
	  		userInfo += "<tr>";
	  		userInfo += "<td>"+user.userId+"</td>";
	  		userInfo += "<td>"+user.userName+"</td>";
	  		userInfo += "<td>"+user.userPassword+"</td>";
	  		userInfo += "<td>"+user.age+"</td>";
	  		userInfo += "</tr>";
	  	}
	  	userInfo += "</table>";
	  	document.getElementById("userInfo").innerHTML = userInfo;
	  }
	  
	  
	  /**
	   获取Map对象
	  */
	  function mapUser(){
	  	var users = myrpc.getUserMapAll();
	  	var size = users.length;
	  	var userInfo = "<table border='1'>";
	  	userInfo += "<tr>";
  		userInfo += "<td>ID</td>";
  		userInfo += "<td>姓名</td>";
  		userInfo += "<td>密码</td>";
  		userInfo += "<td>年龄</td>";
  		userInfo += "</tr>";
	  	var user = '';
	  	for(var u in users){	  	    
	  	    user = users[u];
	  	    if(user.userId == undefined){	  	       
	  	    	break;
	  	    }
	  		userInfo += "<tr>";
	  		userInfo += "<td>"+user.userId+"</td>";
	  		userInfo += "<td>"+user.userName+"</td>";
	  		userInfo += "<td>"+user.userPassword+"</td>";
	  		userInfo += "<td>"+user.age+"</td>";
	  		userInfo += "</tr>";
	  	}
	  	userInfo += "</table>";
	  	document.getElementById("userInfo").innerHTML = userInfo;
	  }
	  
	  
	  function testRegObject(){
	  	alert(rpc.getRpcObj("com.liuzd.json.web.action.TestJson").testHello("欢迎天涯!!"));
	  }  
	
	</script>
  </head>
  
  <body>
     ID: <input type="text" name="userId" id="userId">
     <br>
     姓名: <input type="text" name="userName" id="userName">
     <br>
     密码: <input type="text" name="userPassword" id="userPassword">
     <br>
      年龄:<input type="text" name="age" id="age">
     <br>
     <input type="button" value="测试" onclick="helloName();">
     <br>
     <input type="button" value="获取User" onclick="getUser();">
      <br>
     <input type="button" value="保存User" onclick="saveUser();">
     <br>
     <input type="button" value="List显示" onclick="listUser();">
      <br>
     <input type="button" value="map显示" onclick="mapUser();">
     <br>
     <input type="button" value="测试未注册的对象" onclick="testRegObject();">
     <br>        
     <div id="userInfo">     
     </div>
  </body>
</html>

4 TestJSON.java未注册的使用
A TestJSON.java code
package com.liuzd.json.web.action;
// 不是jcore.jsonrpc.rpcobj包下要进行注册
public class TestJson  implements java.io.Serializable{

	
	private static final long serialVersionUID = 1L;

	public String testHello(String hello){
		return hello;
	}
}

B JS调用方式
 function testRegObject(){
	  	alert(rpc.getRpcObj("com.liuzd.json.web.action.TestJson").testHello("欢迎天涯!!"));
 }  

个人觉得这种方式不错吧!
工程附件说明:
JsonRpcForJava3.2_sample.rar官方示例
TestJsonRPC-project.zip 我的DEMO示例
JSON-RPC-lib.zip 所要的jar重新打包:JSON-RPC.jar文件
  相关解决方案