我正在使用play framework 2.8.x,试图将数据保存到会话中,并在下一个请求中读取此数据,但我的数据未保存在会话对象中。我的控制器类如下所示:

public class UserController extends Controller {
    public Result verifyToken(Http.Request request) {
        final Http.Session session = request.session();
        session.adding("key1", "my_value");
        return ok(userInfo).withCookies(tokenCookie).withSession(session);
    }
}


然后我像下面这样重构我的代码:

public class UserController extends Controller {
    public Result verifyToken(Http.Request request) {
        return ok(userInfo).addingToSession(request, "sessionData", "test");
    }
}


但我有相同的结果。不工作!
然后尝试从Filter的会话中读取数据。我的过滤器如下所示:

public class PageAccessFilter extends Filter {
    @Inject
    public PageAccessFilter(Materializer mat) {
        super(mat);
    }

    @Override
    public CompletionStage<Result> apply(Function<Http.RequestHeader, CompletionStage<Result>> next, Http.RequestHeader rh) {
        final Http.Session userSession = rh.session();
            final String userToken = userSession.get("key1").orElse(null); // in this value was null.
        return next(rh);
    }
}


java - 如何从Session中保存和读取数据?-LMLPHP
如何保存和读取会话中的数据?我做错了什么?

最佳答案

在ok()响应上使用addingToSession

public class UserController extends Controller {
    public Result verifyToken(Http.Request request) {
        return ok(userInfo).addingToSession(request, "key1", "my_value");
    }
}

10-06 12:38
查看更多