package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("stockPrices")//子路徑 public interface StockPriceService extends RemoteService { //客戶端須要的業務方法 StockPrice[] getPrices(String[] symbols); }
實現類以下:java
package com.google.gwt.sample.stockwatcher.server;
import com.google.gwt.sample.stockwatcher.client.StockPrice;
import com.google.gwt.sample.stockwatcher.client.StockPriceService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class StockPriceServiceImpl extends RemoteServiceServlet implements StockPriceService {
public StockPrice[] getPrices(String[] symbols) {
// TODO Auto-generated method stub
return null;
}
}
接下來,要到web.xml中配置servlet:web
<servlet>
<servlet-name>stockPriceServiceImpl</servlet-name>
<servlet-class>com.google.gwt.sample.stockwatcher.server.StockPriceServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>stockPriceServiceImpl</servlet-name>
<url-pattern>/stockwatcher/stockPrices</url-pattern>
</servlet-mapping>
爲了能進行異步調用,還要在客戶端新增一個接口:服務器
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface StockPriceServiceAsync {
void getPrices(String[] symbols, AsyncCallback<StockPrice[]> callback);
}
注意幾點,這個接口的命名須要遵循規範:同步接口後面加Async。app
裏面的方法要遵循規範:方法個數和名稱徹底同樣,可是返回值一概沒有了(由於是異步的),同時參數列表的最後,增長一個AsyncCallback,這是個泛型的容器類,裏面的類別就是同步方法的返回類。這用來調用完成時作些處理。異步
接下來是真正調用的類,這個類命名沒什麼規定,可是要記得他是在client端的,所以有些限制。字體
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);
}
// 實現一個匿名的Callback類
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
public void onFailure(Throwable caught) {
// TODO: Do something with errors.
}
public void onSuccess(StockPrice[] result) {
updateTable(result);
}
};
// 真正的調用
stockPriceSvc.getPrices(stocks.toArray(new String[0]), callback);
}
咱們注意到,真正的調用代碼上並無出現url,那麼GWT的客戶端如何得知要訪問哪一個servlet?答案就在同步interface的annotation中,看藍色字體表示的單詞就明白了。google