我正在将遗留应用程序转换为使用REST api,其中每个方法都需要从会话变量中获取数据(我知道它不是真正的REST应用程序,而是遗留代码)。
我想保留代码DRY,所以我尝试在构造函数中设置会话变量,但HttpServletRequest
在构造期间没有准备好。我想将User
变量放在一个地方。这样做的正确方法是什么?
@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.
}
答案 0 :(得分:1)
"通过使用@Context注释注入JAX-RS SecurityContext实例,可以获得请求的安全信息。注入的安全上下文实例提供HttpServletRequest上可用功能的等效 API"
https://jersey.java.net/documentation/latest/security.html#d0e10543
希望有所帮助