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

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

问题描述

我已经通过Google Web Toolkit StockWatcher教程使用 Eclipse 谷歌插件,我试图对它做一些基本的修改,以便更好地理解RPC框架。



我修改了StockServiceImpl服务器端类的getStocks方法,以便它返回一个Stock对象而不是String对象的数组。该应用程序编译完美,但Google Web Toolkit返回以下错误:

没有源代码可用于com.google.gwt.sample.stockwatcher.server类型.Stock;你忘了继承一个必需的模块吗?



Google Web Toolkit托管模式http://i44.tinypic.com/a47r83.jpg

看起来,客户端类可以'即使该类已被导入,也可以找到Stock对象的实现。作为参考,这是我的包层次结构的截图:

Eclipse Package Hierarchy http://i43.tinypic.com/14tr5gk.jpg

我怀疑我在web.xml中缺少一些东西,但我不知道它是什么。任何人都可以指向正确的方向吗?



编辑:忘记提及股票类是持久性的,所以需要留在服务器端。

解决方案

经过多次试验和错误,我设法找到了一种方法来做到这一点。它可能不是最好的方式,但它的工作原理。希望这篇文章可以节省很多时间和精力。



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



创建股票类的客户端实现



关于GWT,有几点需要注意:


  1. 服务器端类可以导入客户端类,但反之亦然(通常)。
  2. 客户端无法导入任何Google App Engine库(即com.google.appengine.api.users。用户)

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



StockClient.java:



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

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

public class StockClient实现Serializable {

private Long id;
私有字符串符号;
私人日期createDate;

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

public StockClient(字符串符号){
this.symbol = symbol;
this.createDate = new Date();

$ b $ 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;




$ b $ h
$ b

修改客户端类以使用StockClient []而不是字符串[]



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

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:



添加一个导入:

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

除了addStock,loadStocks和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);
}
});

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



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

//股票代码必须介于1到10个字符之间,即数字,字母,
//或点。
if(!symbol.matches(^ [0-9a-zA-Z\\。] {1,10} $)){
Window.alert('+ symbol +'不是有效的符号。);
newSymbolTextBox.selectAll();
return;
}

newSymbolTextBox.setText();

//如果股票已经在表格中,请不要添加股票。
if(stocks.contains(symbol))
return;

addStock(new StockClient(symbol));

$ b 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());
}
});
}



修改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 {
Stock stock = new Stock(getUser(),symbol);
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
尝试{
pm.makePersistent(stock);
} finally {
pm.close();
}
return stock.getId();
}

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

  public StockClient [] getStocks()throws NotLoggedInException {
checkLoggedIn();
PersistenceManager pm = getPersistenceManager();
列出< 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);
清单< Stock>股票=(List< Stock>)q.execute(getUser()); (股票:股票)
{
stockclients.add(new StockClient(stock.getId(),stock.getSymbol(),stock.getCreateDate()));
}
} finally {
pm.close();
}
return(StockClient [])stockclients.toArray(new StockClient [0]);
}



总结



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

  SEVERE :[1244408678890000] javax.servlet.ServletContext log:分派传入的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?"

Google Web Toolkit Hosted Mode http://i44.tinypic.com/a47r83.jpg

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:

Eclipse Package Hierarchy http://i43.tinypic.com/14tr5gk.jpg

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天全站免登陆