如下面一段代码
public class MyApplication implements EntryPoint {
public void onModuleLoad() { // define the service you want to call
MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) svc;
String svUrl = GWT.getModuleBaseURL() + "myService";
endpoint.setServiceEntryPoint(svUrl); // define a handler for what to do when the
// service returns a result
AsyncCallback callback = new AsyncCallback() {
public void onSuccess(Object result) {
RootPanel.get().add(new HTML(result.toString()));
} public void onFailure(Throwable ex) {
RootPanel.get().add(new HTML(ex.toString()));
}
}; // execute the service
svc.myMethod(1, callback); }
}
请问什么时候调用onSuccess,和onFailure方法?

解决方案 »

  1.   

    还有,有时候AsyncCallback 定义的方法参数不只一个,例如
    public interface AnotherCallback { public void onFailure(ClassA a,Throwable t); public void onSuccess(ClassA a,Object rst);
    }
    请问什么时候调用onSuccess,和onFailure方法?
      

  2.   

    你的代码有些乱,我调整了一下。
    调用异步接口之后,一方面,程序会通过异步接口,去访问后台的impl(实现同步接口的servlet);另一方面,还会继续执行svc.myMethod(1, callback)之后的语句,即Window.alert("Async interface has been called.")。也就是说,当你运行时,如果考虑往咯时延,browse页面中会先弹出“Async interface has been called.”提示框,然后才是
    onSuccess中代码的执行。public class MyApplication implements EntryPoint {
        /**入口点*/
        public void onModuleLoad() {
            //异步接口初始化:同步接口转化为异步接口
            MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);
            ServiceDefTarget endpoint = (ServiceDefTarget) svc;
            String svUrl = GWT.getModuleBaseURL() + "myService";
            endpoint.setServiceEntryPoint(svUrl);
            
            //实例化回调函数类
            AsyncCallback callback = new ResultAsyncCallback();
            //调用异步接口
            svc.myMethod(1, callback);  
            //Debug
            Window.alert("Async interface has been called.");
        }
        
        /**回调函数类。用于获取和处理异步接口返回的结果*/
        class  ResultAsyncCallback implements AsyncCallback{
            public void onSuccess(Object result) {
                RootPanel.get().add(new HTML(result.toString()));
            }
            
            public void onFailure(Throwable ex) {
                RootPanel.get().add(new HTML(ex.toString()));
            }
        }
    }
      

  3.   

    b—>s,参数是同步接口的形参,可以多个; s—>b,同步接口的返回值,只有一个,如果你要多个数据,或者是2维的,可以用Vector封装。
      

  4.   

    Hi fish2011,
    我是问什么时候调用onSuccess和onFailure 方法
      

  5.   

    svc.myMethod(1, callback)执行之后,有结果返回了,才会执行onSuccess 或者 onFailure里的代码。
      

  6.   

    onSuccess和onFailure 方法是由ajax框架调用的。
      

  7.   

    那我怎样才能调用onFailure 方法呢?
      

  8.   

    我kao,你给后台整点错,或者把servlet配制成错误的,ajax会自动调用onFailure。
      

  9.   

    查了一些文档,好像是说根据myMethod的返回值类型决定的。
    当类型为Object类型或null时调用onSuccess方法,为Throwable类型时调用onFailure方法。
    不知道对不对。