我正在使用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);
}
}
如何保存和读取会话中的数据?我做错了什么?
最佳答案
在ok()响应上使用addingToSession
。
public class UserController extends Controller {
public Result verifyToken(Http.Request request) {
return ok(userInfo).addingToSession(request, "key1", "my_value");
}
}