[英]Centralizing getting of a session variable in a Jersey REST resource
我正在將舊版應用程序轉換為使用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.
}
“可以通過使用@Context注釋注入JAX-RS SecurityContext實例來獲得請求的安全信息。注入的安全上下文實例提供了與HttpServletRequest API 上可用功能等效的功能 ”
https://jersey.java.net/documentation/latest/security.html#d0e10543
希望能有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.