如何在 JSF 的会话范围内获取和设置对象? [英] How do I get and set an object in session scope in JSF?

查看:33
本文介绍了如何在 JSF 的会话范围内获取和设置对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要在 JSF 应用程序的会话范围内保留一个对象.我在哪里定义会话变量,以及如何从视图文件或支持 bean 获取和设置它?

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 backing bean?

推荐答案

两种通用方式:

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

然后:

SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");

  • 或者,将其设为 @SessionScoped bean 的属性,您将其注入 @RequestScoped bean.

  • Or, make it a property of a @SessionScoped bean which you inject in your @RequestScoped bean.

    sessionBean.setSomeVariable(yourVariable);
    

    然后:

    SomeObject yourVariable = sessionBean.getSomeVariable();
    

    您可以通过@Inject@Named @SessionScoped 转化为@Named @RequestScoped.

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

    @Inject
    private SessionBean sessionBean;
    

    或者,如果您还没有使用 CDI,您可以通过 @ManagedProperty@ManagedBean @SessionScoped 转换为 @ManagedBean @RequestScoped代码>.

    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
    

  • 这篇关于如何在 JSF 的会话范围内获取和设置对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆