您可以在客戶端上通過以下方式使用GWT RPC:
創建服務
private void refreshWatchList() {
final double MAX_PRICE = 100.0; // $100.00
final double MAX_PRICE_CHANGE = 0.02; // +/- 2%
StockPrice[] prices = new StockPrice[stocks.size()];
for (int i = 0; i < stocks.size(); i++) {
double price = Random.nextDouble() * MAX_PRICE;
double change = price * MAX_PRICE_CHANGE
* (Random.nextDouble() * 2.0 - 1.0);
prices[i] = new StockPrice(stocks.get(i), price, change);
}
updateTable(prices);
}
定義服務
@RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(String[] symbols);
}
實現服務
public class StockPriceServiceImpl extends RemoteServiceServlet implements StockPriceService {
public StockPrice[] getPrices(String[] symbols) {
// TODO Auto-generated method stub
return null;
}
}
調用來自客戶端的服務,使遠程過程調用:
private ArrayList<String> stocks = new ArrayList<String>();
private StockPriceServiceAsync stockPriceSvc = GWT.create(StockPriceService.class);
private void refreshWatchList() {
// Initialize the service proxy.
if (stockPriceSvc == null) {
stockPriceSvc = GWT.create(StockPriceService.class);
}
// Set up the callback object.
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
}
public void onSuccess(StockPrice[] result) {
updateTable(result);
}
};
// Make the call to the stock price service.
stockPriceSvc.getPrices(stocks.toArray(new String[0]), callback);
}
這基本上就是RPC完成。
在中間
你
鍵可能是你對象的序列化的結果。如果你不喜歡,你也可以使用GWT RequestBuilder
。
RequestBuilder requestBuilder = new RequestBuilder(requestMethod, url);
requestBuilder.setHeader("Content-Type", "application/json");
requestBuilder.setRequestData(bodyString);
requestBuilder.setCallback(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
callback.onResponse(response.getStatusCode(), response.getText());
}
@Override
public void onError(Request request, Throwable exception) {
callback.onError(new Exception(exception));
}
});
try {
requestBuilder.send();
}
catch(RequestException ex) {
callback.onError(ex);
}
使用RequestBuilder時,您可以更好地控制格式和正在傳輸的內容。
請添加您正在調用的遠程過程的方法簽名。 – Baz
在問這個問題之前,你有沒有做過任何研究? GWT是開源的,它應該很容易追蹤「罪魁禍首」 - 檢查由GWT編譯器從您的* Async接口生成的類,查看哪些類在那裏使用,並跟蹤直到找到序列化方案。或谷歌周圍... –