【问题标题】:Play Framework 2.7: How to update session within a Action composition in JavaPlay Framework 2.7:如何在 Java 中的 Action 组合中更新会话
【发布时间】:2019-08-16 07:44:56
【问题描述】:

我正在尝试将应用从 Play 2.7 更新。我看到现在通过 Http.Context 访问会话对象已被弃用。相反,我必须使用 Http.Request 对象。此外,在我可以立即更改 Session 对象之前 - 现在看来我必须创建一个新的 Session 和 add to the Result by myself。但是如何在我无法访问 Result 对象的 Action 组合中实现这一点?

Action 组合可能如下所示:

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

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

编辑:

我找不到简单的解决方案,只能找到第二个操作注释的解决方法。可以通过.thenApply 访问 Result 对象并附加新的 Session 对象。

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

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

【问题讨论】:

    标签: java playframework


    【解决方案1】:

    由 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;
              }
            });
          }
    
        };
      }
    
    }
    

    【讨论】:

    • 谢谢,但我想在 Action 组合中这样做 - 在 Action 中它是直截了当的。
    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 2018-10-14
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多