2

我想在超时等于 5s 时重定向到另一个 url。

我拥有的代码:

private void timeout(RoutingContext handler) {
    vertx.setPeriodic(5000, new Handler<Long>() {
        @Override
        public void handle(Long aLong) {
            System.out.println("Session expired : " + aLong);       
            handler.response().putHeader("location","/logout").setStatusCode(302).end();
        }
    });
}

我得到的错误是:

java.lang.IllegalStateException: Response has already been written"
4

2 回答 2

0

当响应已经写入时,您不能更改标头。但是你可以检查这个条件并写:

public void handle(Long aLong) {
    if (!handler.response().headWritten()) 
        handler.response().putHeader("location","/logout").setStatusCode(302).end();
}
于 2016-02-10T09:43:44.967 回答
0

您需要一个简单的计时器而不是周期性计时器:

private void timeout(RoutingContext ctx) {
    long tid = ctx.vertx().setTimer(5000, t -> {
        ctx.response().putHeader("location","/logout").setStatusCode(302).end();
    });
    ctx.addBodyEndHandler(v -> ctx.vertx().cancelTimer(tid));
}

并且不要忘记取消计时器以防没有超时!

于 2016-02-15T12:15:09.507 回答