Bạn có thể sử dụng GWT RPC theo cách sau trên máy khách:
Tạo một dịch vụ
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);
}
Xác định dịch vụ
@RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(String[] symbols);
}
Thực hiện dịch vụ
public class StockPriceServiceImpl extends RemoteServiceServlet implements StockPriceService {
public StockPrice[] getPrices(String[] symbols) {
// TODO Auto-generated method stub
return null;
}
}
Gọi dịch vụ từ khách hàng và thực hiện cuộc gọi thủ tục từ xa:
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);
}
này về cơ bản là những gì RPC được thực hiện.
bạn
phím ở giữa
có lẽ là kết quả của serialization đối tượng của bạn. Nếu bạn không thích điều đó, bạn cũng có thể sử dụng 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);
}
Khi sử dụng RequestBuilder bạn có nhiều quyền kiểm soát định dạng và nội dung đang được vận chuyển.
Vui lòng thêm chữ ký phương thức của quy trình từ xa bạn đang gọi. – Baz
Bạn đã * thực hiện bất kỳ nghiên cứu nào trước khi đặt câu hỏi này? GWT là mã nguồn mở và dễ dàng theo dõi "thủ phạm" - kiểm tra các lớp được tạo ra từ giao diện '* Async' của trình biên dịch GWT, xem các lớp nào được sử dụng ở đó và đi theo đường cho tới khi bạn tìm thấy lược đồ tuần tự hóa . Hoặc google xung quanh ... –