Java 在REST资源中集中获取会话变量 问题定义
我正在将一个遗留应用程序转换为使用RESTAPI,其中每个方法都需要从会话变量获取数据(我知道它不是真正的REST应用程序,但它是遗留代码) 我希望保持代码干燥,因此我尝试在构造函数中设置会话变量,但是Java 在REST资源中集中获取会话变量 问题定义,java,jersey,Java,Jersey,我正在将一个遗留应用程序转换为使用RESTAPI,其中每个方法都需要从会话变量获取数据(我知道它不是真正的REST应用程序,但它是遗留代码) 我希望保持代码干燥,因此我尝试在构造函数中设置会话变量,但是HttpServletRequest在构造过程中没有准备好。我想在一个地方设置User变量。正确的方法是什么 代码示例 “通过使用@Context注释注入JAX-RS SecurityContext实例,可以获得请求的安全信息。注入的安全上下文实例提供了HttpServletRequest上可用功
HttpServletRequest
在构造过程中没有准备好。我想在一个地方设置User
变量。正确的方法是什么
代码示例
“通过使用@Context注释注入JAX-RS SecurityContext实例,可以获得请求的安全信息。注入的安全上下文实例提供了HttpServletRequest上可用功能的等效功能。”
希望有帮助
@Path("/someResource")
public class SomeResource {
@Context
HttpServletRequest currentRequest;
private User user = null;
public SomeResource() {
// This doesn't work
// HttpSession session = currentRequest.getSession();
// user = (User) session.getAttribute("user");
}
@GET
@Produces ( ... )
@PermitAll
@Path( ... )
public findById read(...) {
HttpSession session = currentRequest.getSession();
User user = (User) session.getAttribute("user");
...
}
@GET
@Produces ( ... )
@PermitAll
@Path( ... )
public findByName read(...) {
HttpSession session = currentRequest.getSession();
User user = (User) session.getAttribute("user");
...
}
@GET
@Produces ( ... )
@PermitAll
@Path( ... )
public someResource findAll (...) {
HttpSession session = currentRequest.getSession();
User user = (User) session.getAttribute("user");
...
}
... many other paths, etc... each checking the user session variable.
}