使用 Google Web Toolkit 和 JSON开发Ajax应用程序

http://tech.ddvip.com   2007年08月25日    社区交流

内容摘要:本文介绍如何使用 Google Web Toolkit(GWT) 和 JSON 开发一个示例 Ajax 应用程序。作者将分别介绍如何在客户端使用 GWT 的 JSON API 来解析和生成 JSON 编码的数据,以及如何在服务器端使用 GWT 的 RemoteServiceServlet 来接受和回复来自客户端的请求,并使用 SOJO 来解析处理 JSON 数据。

  示例程序以 GWT 的 RemoteServiceServlet 类作为服务器端请求响应的 servlet 的基类。并且使用了 SOJO 作为服务器端 JavaBean 和 JSON 格式数据相互转换的工具,来处理 JSON 格式的信息。

  模拟测试过程

  因为本文提供的程序为示例程序,所以测试过程使用 TestRunner 类来模拟测试运行的过程。当 RunTestServlet 接收到客户端运行测试请求的时候,会创建一个 TestRunner 对象,并调用 TestRunner.start() 来启动测试线程。TestRunner 的方法包括:

  init():初始化模拟测试类。

  run(): 当起动测试工具时,启动 TestRunner 线程,run() 方法被调用。作为模拟测试,在 run() 方法里面会实时的更新测试结果,并记录下测试起止时间,测试结果等数值。

  getTestResults():得到当前测试运行的结果。

清单 12. TestRunner 的模拟测试实现

public class TestRunner extends Thread{
  private List testResults;
  private int caseNum = 0;
  private String[] suiteNames = null;
  public void init(int caseNum, String[] suiteNames) {
    testResults= new ArrayList();
    this.suiteNames = suiteNames;
    this.caseNum = caseNum;
    }
/**
* invoke the server-side test tool
*/
public void run() {
  // simulate the running test tool
  for (int j = 0; j < suiteNames.length; j++) {
    for (int i = 0; i < caseNum; i++) {
      TestResult tr = new TestResult();
      tr.setName(suiteNames[j] + "-case-" + i);
      tr.setStart(new Date().toString());
      try { //simulate the test
        Thread.sleep(1200);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      tr.setEnd(new Date().toString());
      tr.setResult(genRandomResult());
      testResults.add(tr);
    }
  }
}
/**
* simulate test results
* @return
*/
private String genRandomResult(){
  int result = new Random().nextInt(3);
  return result==1?"FAIL":"PASS";
}
/**
* read the dynamic test results (such as result log file)
*/
public List getTestResults(){
  return this.testResults;
  }
}

  服务器端 JSON 数据的解析和转换

来源:ibm    作者:邹林志    责编:豆豆技术应用

正在加载评论...