簡體   English   中英

在Jersey REST資源中集中獲取會話變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM