在XMLHttpRequest上处理Jersey(JAX-RS)中止

时间:2016-01-15 15:52:14

标签: java jersey xmlhttprequest jax-rs abort

我使用Jersey作为应用程序的REST API,请考虑以下函数

@POST
public String writeSomething() {
    someVeryIntensiveTaskWhichTaking("5 seconds");
    Log.info("get request fulfilled") // don't want the logging to happen if user cancelled on UI
    return "ok";
}

假设此POST请求正在执行某项密集型任务,最多可能需要5秒钟。然后在用户界面上,用户决定在2秒后通过XMLHttpRequest.abort()取消POST请求,

有没有办法跟踪这次堕胎并阻止某些行动?比如检查IsClientConnected

更新#1

感谢peeskillet的提示,但我还是无法在XHR堕胎时触发回调。以下是我的代码

@POST
public String writeSomething(@Suspended final AsyncResponse asyncResponse) {
    asyncResponse.register(new ConnectionCallback() {
        public void onDisconnect(AsyncResponse asyncResponse) {
            System.out.println("This is canceled, do whatever you want"); // this is not triggered after XHR aborted
        }
    });
    someVeryIntensiveAsynTaskWhichTaking("5 seconds", asyncResponse); // this asyn function will trigger asyncResponse.resume() upon completion
}

0 个答案:

没有答案