通过 GWT RPC 传递类对象的问题 [英] Problems passing class objects through GWT RPC

查看:23
本文介绍了通过 GWT RPC 传递类对象的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了 Google Web Toolkit

客户端类似乎无法找到 Stock 对象的实现,即使该类已被导入.作为参考,这是我的包层次结构的屏幕截图:

我怀疑我在 web.xml 中遗漏了一些东西,但我不知道它是什么.有人能指出我正确的方向吗?

忘记提到 Stock 类是可持久化的,所以它需要留在服务器端.

解决方案

经过多次反复试验,我设法找到了一种方法来做到这一点.这可能不是最好的方法,但它有效.希望这篇文章可以为其他人节省很多时间和精力.

这些说明假设您已完成基本的 StockWatcher 教程以及 Google App Engine StockWatcher 修改.

创建 Stock 类的客户端实现

关于 GWT 有几点需要牢记:

  1. 服务器端类可以导入客户端类,但反过来不行(通常).
  2. 客户端无法导入任何 Google App Engine 库(即 com.google.appengine.api.users.User)

由于上述两个原因,客户端永远无法实现我们在 com.google.gwt.sample.stockwatcher.server 中创建的 Stock 类.相反,我们将创建一个名为 StockClient 的新客户端 Stock 类.

StockClient.java:

package com.google.gwt.sample.stockwatcher.client;导入 java.io.Serializable;导入 java.util.Date;公共类 StockClient 实现了 Serializable {私人长ID;私有字符串符号;私人日期创建日期;公共股票客户端(){this.createDate = new Date();}公共 StockClient(字符串符号){this.symbol = 符号;this.createDate = new Date();}公共 StockClient(长 ID,字符串符号,日期 createDate){这();this.id = id;this.symbol = 符号;this.createDate = createDate;}公共长 getId() {返回 this.id;}公共字符串 getSymbol() {返回 this.symbol;}公共日期 getCreateDate() {返回 this.createDate;}公共无效setId(长id){this.id = id;}公共无效setSymbol(字符串符号){this.symbol = 符号;}}

修改客户端类以使用 StockClient[] 而不是 String[]

现在我们对客户端类进行一些简单的修改,以便它们知道 RPC 调用返回 StockClient[] 而不是 String[].

StockService.java:

package com.google.gwt.sample.stockwatcher.client;导入 com.google.gwt.sample.stockwatcher.client.NotLoggedInException;导入 com.google.gwt.user.client.rpc.RemoteService;导入 com.google.gwt.user.client.rpc.RemoteServiceRelativePath;@RemoteServiceRelativePath("股票")公共接口 StockService 扩展了 RemoteService {public Long addStock(String symbol) 抛出 NotLoggedInException;public void removeStock(String symbol) 抛出 NotLoggedInException;public StockClient[] getStocks() 抛出 NotLoggedInException;}

StockServiceAsync.java:

package com.google.gwt.sample.stockwatcher.client;导入 com.google.gwt.sample.stockwatcher.client.StockClient;导入 com.google.gwt.user.client.rpc.AsyncCallback;公共接口 StockServiceAsync {public void addStock(字符串符号,AsyncCallback异步);public void removeStock(字符串符号,AsyncCallback异步);public void getStocks(AsyncCallback async);}

StockWatcher.java:

添加一个导入:

import com.google.gwt.sample.stockwatcher.client.StockClient;

所有其他代码保持不变,除了 addStock、loadStocks 和 displayStocks:

private void loadStocks() {stockService = GWT.create(StockService.class);stockService.getStocks(new AsyncCallback() {public void onFailure(抛出错误){句柄错误(错误);}公共无效onSuccess(字符串[]符号){显示股票(符号);}});}私有无效显示股票(字符串 [] 符号){for(字符串符号:符号){displayStock(符号);}}私有无效 addStock() {最终字符串符号 = newSymbolTextBox.getText().toUpperCase().trim();newSymbolTextBox.setFocus(true);//股票代码必须在 1 到 10 个字符之间,包括数字、字母、//或点.if (!symbol.matches("^[0-9a-zA-Z\.]{1,10}$")) {Window.alert("'" + 符号 + "' 不是有效符号.");newSymbolTextBox.selectAll();返回;}newSymbolTextBox.setText("");//如果它已经在表中,不要添加股票.如果(股票.包含(符号))返回;addStock(new StockClient(symbol));}私有无效 addStock(最终 StockClient 股票){stockService.addStock(stock.getSymbol(), new AsyncCallback() {public void onFailure(抛出错误){句柄错误(错误);}公共无效onSuccess(长ID){stock.setId(id);displayStock(stock.getSymbol());}});}

修改 StockServiceImpl 类以返回 StockClient[]

最后,我们修改 StockServiceImpl 类的 getStocks 方法,使其在返回数组之前将服务器端 Stock 类转换为客户端 StockClient 类.

StockServiceImpl.java

import com.google.gwt.sample.stockwatcher.client.StockClient;

我们需要稍微改变 addStock 方法,以便返回生成的 ID:

public Long addStock(String symbol) throws NotLoggedInException {股票股票=新股票(getUser(),符号);检查登录();PersistenceManager pm = getPersistenceManager();尝试 {pm.makePersistent(股票);} 最后 {下午.关闭();}返回 stock.getId();}

所有其他方法保持不变,除了 getStocks:

public StockClient[] getStocks() 抛出 NotLoggedInException {检查登录();PersistenceManager pm = getPersistenceManager();列表stockclients = new ArrayList();尝试 {查询 q = pm.newQuery(Stock.class, "user == u");q.declareParameters("com.google.appengine.api.users.User u");q.setOrdering("createDate");列表<库存>股票 = (List) q.execute(getUser());为(股票:股票){stockclients.add(new StockClient(stock.getId(), stock.getSymbol(), stock.getCreateDate()));}} 最后 {下午.关闭();}返回 (StockClient[]) stockclients.toArray(new StockClient[0]);}

总结

上面的代码在部署到 Google App Engine 时非常适合我,但在 Google Web Toolkit 托管模式下会触发错误:

SEVERE:[1244408678890000] javax.servlet.ServletContext 日志:调度传入的 RPC 调用时出现异常com.google.gwt.user.server.rpc.UnexpectedException: 服务方法 'public abstract com.google.gwt.sample.stockwatcher.client.StockClient[] com.google.gwt.sample.stockwatcher.client.StockService.getStocks() 抛出 com.google.gwt.sample.stockwatcher.client.NotLoggedInException' 抛出意外异常:java.lang.NullPointerException: Name is null

如果您遇到同样的问题,请告诉我.它在 Google App Engine 中运行的事实似乎表明托管模式中存在错误.

I've run through the Google Web Toolkit StockWatcher Tutorial using Eclipse and the Google Plugin, and I'm attempting to make some basic changes to it so I can better understand the RPC framework.

I've modified the "getStocks" method on the StockServiceImpl server-side class so that it returns an array of Stock objects instead of String objects. The application compiles perfectly, but the Google Web Toolkit is returning the following error:

"No source code is available for type com.google.gwt.sample.stockwatcher.server.Stock; did you forget to inherit a required module?"

It seems that the client-side classes can't find an implementation of the Stock object, even though the class has been imported. For reference, here is a screenshot of my package hierarchy:

I suspect that I'm missing something in web.xml, but I have no idea what it is. Can anyone point me in the right direction?

EDIT: Forgot to mention that the Stock class is persistable, so it needs to stay on the server-side.

解决方案

After much trial and error, I managed to find a way to do this. It might not be the best way, but it works. Hopefully this post can save someone else a lot of time and effort.

These instructions assume that you have completed both the basic StockWatcher tutorial and the Google App Engine StockWatcher modifications.

Create a Client-Side Implementation of the Stock Class

There are a couple of things to keep in mind about GWT:

  1. Server-side classes can import client-side classes, but not vice-versa (usually).
  2. The client-side can't import any Google App Engine libraries (i.e. com.google.appengine.api.users.User)

Due to both items above, the client can never implement the Stock class that we created in com.google.gwt.sample.stockwatcher.server. Instead, we'll create a new client-side Stock class called StockClient.

StockClient.java:

package com.google.gwt.sample.stockwatcher.client;

import java.io.Serializable;
import java.util.Date;

public class StockClient implements Serializable {

  private Long id;
  private String symbol;
  private Date createDate;

  public StockClient() {
    this.createDate = new Date();
  }

  public StockClient(String symbol) {
    this.symbol = symbol;
    this.createDate = new Date();
  }

  public StockClient(Long id, String symbol, Date createDate) {
    this();
    this.id = id;
    this.symbol = symbol;
    this.createDate = createDate;
  }

  public Long getId() {
      return this.id;
  }

  public String getSymbol() {
      return this.symbol;
  }

  public Date getCreateDate() {
      return this.createDate;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setSymbol(String symbol) {
      this.symbol = symbol;
  }
}

Modify Client Classes to Use StockClient[] instead of String[]

Now we make some simple modifications to the client classes so that they know that the RPC call returns StockClient[] instead of String[].

StockService.java:

package com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.sample.stockwatcher.client.NotLoggedInException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("stock")
public interface StockService extends RemoteService {
  public Long addStock(String symbol) throws NotLoggedInException;
  public void removeStock(String symbol) throws NotLoggedInException;
  public StockClient[] getStocks() throws NotLoggedInException;
}

StockServiceAsync.java:

package com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.sample.stockwatcher.client.StockClient;
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface StockServiceAsync {
  public void addStock(String symbol, AsyncCallback<Long> async);
  public void removeStock(String symbol, AsyncCallback<Void> async);
  public void getStocks(AsyncCallback<StockClient[]> async);
}

StockWatcher.java:

Add one import:

import com.google.gwt.sample.stockwatcher.client.StockClient;

All other code stays the same, except addStock, loadStocks, and displayStocks:

private void loadStocks() {
    stockService = GWT.create(StockService.class);
    stockService.getStocks(new AsyncCallback<String[]>() {
        public void onFailure(Throwable error) {
            handleError(error);
        }

        public void onSuccess(String[] symbols) {
            displayStocks(symbols);
        }
    });
}

private void displayStocks(String[] symbols) {
    for (String symbol : symbols) {
        displayStock(symbol);
    }
}

private void addStock() {
    final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
    newSymbolTextBox.setFocus(true);

    // Stock code must be between 1 and 10 chars that are numbers, letters,
    // or dots.
    if (!symbol.matches("^[0-9a-zA-Z\.]{1,10}$")) {
        Window.alert("'" + symbol + "' is not a valid symbol.");
        newSymbolTextBox.selectAll();
        return;
    }

    newSymbolTextBox.setText("");

    // Don't add the stock if it's already in the table.
    if (stocks.contains(symbol))
        return;

    addStock(new StockClient(symbol));
}

private void addStock(final StockClient stock) {
    stockService.addStock(stock.getSymbol(), new AsyncCallback<Long>() {
        public void onFailure(Throwable error) {
            handleError(error);
        }

        public void onSuccess(Long id) {
            stock.setId(id);
            displayStock(stock.getSymbol());
        }
    });
}

Modify the StockServiceImpl Class to Return StockClient[]

Finally, we modify the getStocks method of the StockServiceImpl class so that it translates the server-side Stock classes into client-side StockClient classes before returning the array.

StockServiceImpl.java

import com.google.gwt.sample.stockwatcher.client.StockClient;

We need to change the addStock method slightly so that the generated ID is returned:

public Long addStock(String symbol) throws NotLoggedInException {
  Stock stock = new Stock(getUser(), symbol);
  checkLoggedIn();
  PersistenceManager pm = getPersistenceManager();
  try {
    pm.makePersistent(stock);
  } finally {
    pm.close();
  }
  return stock.getId();
}

All other methods stay the same, except getStocks:

public StockClient[] getStocks() throws NotLoggedInException {
  checkLoggedIn();
  PersistenceManager pm = getPersistenceManager();
  List<StockClient> stockclients = new ArrayList<StockClient>();
  try {
    Query q = pm.newQuery(Stock.class, "user == u");
    q.declareParameters("com.google.appengine.api.users.User u");
    q.setOrdering("createDate");
    List<Stock> stocks = (List<Stock>) q.execute(getUser());
    for (Stock stock : stocks)
    {
       stockclients.add(new StockClient(stock.getId(), stock.getSymbol(), stock.getCreateDate()));
    }
  } finally {
    pm.close();
  }
  return (StockClient[]) stockclients.toArray(new StockClient[0]);
}

Summary

The code above works perfectly for me when deployed to Google App Engine, but triggers an error in Google Web Toolkit Hosted Mode:

SEVERE: [1244408678890000] javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract com.google.gwt.sample.stockwatcher.client.StockClient[] com.google.gwt.sample.stockwatcher.client.StockService.getStocks() throws com.google.gwt.sample.stockwatcher.client.NotLoggedInException' threw an unexpected exception: java.lang.NullPointerException: Name is null

Let me know if you encounter the same problem or not. The fact that it works in Google App Engine seems to indicate a bug in Hosted Mode.

这篇关于通过 GWT RPC 传递类对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆