如何在JSF托管Bean中创建,访问和销毁会话? [英] How to create, access and destroy session in JSF managed bean?

查看:70
本文介绍了如何在JSF托管Bean中创建,访问和销毁会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在为在线购物车创建一个Web应用程序,并且需要在每个jsf页面上维护会话.

Currently, I am creating a web application for an online shopping cart and I need to maintain session on each jsf page..

我的问题是:

  1. 如何在托管bean中创建和销毁会话

  1. How can I create and destroy session in managed bean

如何访问存储在会话变量中的值?像这样?

How can I access value stored in session variable? Like this?

FacesContext.getCurrentInstance().getExternalContext().getSessionMap.put("key",object);

  • 如何销毁jsf中的会话

  • How can I destroy a session in jsf

    我还需要使用session.invalidate()销毁会话,但是我失败了!

    I also need to destroy the session using session.invalidate() but i am failed !!

    推荐答案

    如何在托管bean中创建和销毁会话

    您不需要自己创建它. servletcontainer将根据需要自动为您完成此操作.换句话说,每当您(或JSF)需要在会话范围内设置对象时,servlet容器都会自动创建会话.在JSF Web应用程序中,当您

    You don't need to create it yourself. The servletcontainer will do it automatically for you on demand. In other words, whenever you (or JSF) need to set an object in the session scope, then the servletcontainer will automatically create the session. In a JSF web application, this will happen when you

    • 第一次引用@SessionScoped@ViewScoped托管bean.
    • 通过ExternalContext#getSession()获取会话,第一次通过true.
    • 第一次由ExternalContext#getSessionMap()在会话映射中存储对象.
    • 在状态保存方法设置为服务器"时,第一次用<h:form>返回页面.
    • Reference a @SessionScoped or @ViewScoped managed beanfor the first time.
    • Obtain the session by ExternalContext#getSession(), passing true for the first time.
    • Store an object in session map by ExternalContext#getSessionMap() for the first time.
    • Return a page with a <h:form> for the first time while the state saving method is set to "server".

    您可以通过ExternalContext#invalidateSession()销毁会话.例如

    You can destroy the session by ExternalContext#invalidateSession(). E.g.

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "login?faces-redirect=true";
    }
    

    请记住以后再发送重定向,因为会话对象在当前请求的响应中仍然可用,但在下一个请求中不再可用.

    Remember to send a redirect afterwards, because the session objects are still available in the response of the current request, but not anymore in the next request.

    如何访问存储在会话变量中的值?

    只需将其设置为@SessionScoped受管bean的属性即可.另外,您也可以手动操作ExternalContext#getSessionMap(),是的.

    Just make it a property of a @SessionScoped managed bean. Alternatively, you can also manually manipulate the ExternalContext#getSessionMap(), yes.

    如何销毁jsf中的会话

    在第一个问题中已经回答了这个问题.

    This is already answered in the first question.

    • How do servlets work? Instantiation, sessions, shared variables and multithreading
    • Basic steps for starting session in jsf
    • How to choose the right bean scope?

    这篇关于如何在JSF托管Bean中创建,访问和销毁会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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