How do I get and set an object in session scope in JSF?

前端 未结 3 1774
情书的邮戳
情书的邮戳 2020-12-07 16:18

I need to persist just one object in session scope of my JSF application. Where do I define a session variable, and how do I get and set it from either a view file or backin

3条回答
  •  孤城傲影
    2020-12-07 16:51

    Two general ways:

    • Store it in ExternalContext#getSessionMap()

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      Map sessionMap = externalContext.getSessionMap();
      sessionMap.put("somekey", yourVariable);
      

      And then later:

      SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");
      
    • Or, make it a property of a @SessionScoped bean which you inject in your @RequestScoped bean.

      sessionBean.setSomeVariable(yourVariable);
      

      And then later:

      SomeObject yourVariable = sessionBean.getSomeVariable();
      

      You can get a @Named @SessionScoped into a @Named @RequestScoped via @Inject.

      @Inject
      private SessionBean sessionBean;
      

      Or, if you're not using CDI yet, you can get a @ManagedBean @SessionScoped into a @ManagedBean @RequestScoped via @ManagedProperty.

      @ManagedProperty("#{sessionBean}")
      private SessionBean sessionBean; // +getter+setter
      

提交回复
热议问题