我只需要在 JSF 应用程序的 session 范围内保留一个对象。在哪里定义 session 变量,以及如何从 View 文件或支持 bean 获取和设置它?
最佳答案
两种一般方法:
将其存储在
ExternalContext#getSessionMap()
中ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); Map<String, Object> sessionMap = externalContext.getSessionMap(); sessionMap.put("somekey", yourVariable);
然后:
SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");
或者,将其设为
@SessionScoped
的属性您在@RequestScoped
中注入(inject)的 bean bean 。sessionBean.setSomeVariable(yourVariable);
然后:
SomeObject yourVariable = sessionBean.getSomeVariable();
您可以获得
@Named @SessionScoped
进入@Named @RequestScoped
通过@Inject
.@Inject private SessionBean sessionBean;
或者,如果您尚未使用 CDI,您可以获得
@ManagedBean @SessionScoped
进入@ManagedBean @RequestScoped
通过@ManagedProperty
.@ManagedProperty("#{sessionBean}") private SessionBean sessionBean; // +getter+setter
关于jsf - 如何在 JSF 中获取和设置 session 范围内的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495404/