问题
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 :
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);
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()
, passingtrue
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