繁体   English   中英

Play Framework 2.7:如何在Java中的动作组合中更新会话

[英]Play Framework 2.7: How to update session within a Action composition in Java

我正在尝试将应用程序从Play 2.7更新。 我看到现在不赞成通过Http.Context访问会话对象。 相反,我必须使用Http.Request对象。 另外,在我可以立即更改Session对象之前-现在看来我必须创建一个新的Session并自己添加到Result中 但是,如何在无法访问Result对象的Action组合中实现此目标?

一个动作组成看起来像:

public class VerboseAction extends play.mvc.Action.Simple {
  public CompletionStage<Result> call(Http.Request req) {
    ...
    return delegate.call(req);
  }
}

我在这里看不到如何向会话添加内容!

编辑:

我找不到简单的解决方案,但找到了带有第二个动作注释的解决方法。 可以通过.thenApply访问Result对象并.thenApply新的Session对象。

public CompletionStage<Result> call(Http.Request request) {
  return delegate.call(request).thenApply(result -> {
     Http.Session session = ... change the session  
     return result.withSession(session);
  });
}

如果有人对如何直接在动作组成中更改会话有更好的主意,请随时回答。

会话由withNewSession()清除。 当您使用addingToSession(...)添加某些内容时(可能是在登录后),会创建一个新会话。 这是我完整的工作代码:我有2个时间戳:一个用于日志文件,一个用于应用程序超时。

public class ActionCreator implements play.http.ActionCreator {
  private final int msTimeout;

  @Inject
  public ActionCreator(Config config) {
    this.msTimeout = config.getInt("application.msTimeout");
  }

  @Override
  public Action<?> createAction(Http.Request request, Method actionMethod) {
    return new Action.Simple() {

      @Override
      public CompletionStage<Result> call(Http.Request req) {

        // add timestamp for the elapsed time in log
        req.getHeaders().addHeader("x-log-timestamp", "" + System.currentTimeMillis());

        // did a session timeout occur
        boolean timeout = SessionUtils.isTimeout(req, msTimeout);

        // apply current action 
        return delegate.call(req).thenApply(result -> {

          // display some info in log
          Utils.logInfo(req);

          // return final result
          if (timeout) {
            return result.withNewSession();
          } else if (SessionUtils.isOpen(req)) {
            return result.addingToSession(req, "timestamp", "" + System.currentTimeMillis());
          } else {
            return result;
          }
        });
      }

    };
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM