How to create, access and destroy session in JSF managed bean?

一个人想着一个人 提交于 2020-03-20 06:30:39

问题


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

My questions are :

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

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

    FacesContext.getCurrentInstance().getExternalContext().getSessionMap.put("key",object);
    
  3. How can I destroy a session in jsf

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


回答1:


How can I create and destroy session in managed bean

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

  • 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".

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.


How can I access value stored in session variable?

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


How can I destroy a session in jsf

This is already answered in the first question.

See also:

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


来源:https://stackoverflow.com/questions/14184149/how-to-create-access-and-destroy-session-in-jsf-managed-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!