Wednesday, September 8, 2010

Interacting with Session Objects in JSF.


In this session I will try to bring small tips n tricks to lime light for enhancing JSF capabilities. We will first see how an user information is tracked in session.

Setting Session object in jsf:

Code Snippet-1




FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
context.getExternalContext().getSession(true);
session.setAttribute("emailid",this.getEmaillogin());
session.setAttribute("networkID",this.getNetworkId());

InetAddress thisIp = InetAddress.getLocalHost();
String ip=thisIp.getHostAddress();
String reg_geography=TimeZone.getDefault().getID();




Getting Session object in jsf:

Code Snippet-2




FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)
context.getExternalContext().getSession(true);
setEmailid(session.getAttribute("emailid").toString());




Terminating Session object in jsf:

Code Snippet-3



HttpSession session = (HttpSession)
FacesContext.getCurrentInstance().getExternalContext().getSession(false);
FacesUtils.resetManagedBean("UserRegistration");
if (session != null) {
session.invalidate();
}



Explanation:

Conceptually, you can think of FacesContext as the class that has all the stuff you need to interact with the UI and the rest of the JSF environment. The JSF implementation will either create a new instance for each request or choose one from a pool of available instances. Either way, there will be an instance available to you any time your application is interacting with a user.Technically, it represents the state of the current HTTP request.


For accessing the latest session object we need to call the getSession() based upon the current thread (context).Once we have the session object we can play around its given methods like setAttribute() and getAttribute().



The setAttribute() as its name suggests , it sets the attributes to a String object like “emailid” and “networkId” in our case illustrated in Code Snippet -1.After setting the String Object , the next step is to access it .This is accomplished by the getAttribute() method which we have to base it on the String Object like “emailid” in the Code Snippet -2.



Once we are done with the manipulation of the Session Object , the next big thing that comes to our mind is how to terminate the session.For achieving the above objective we require two methods i.e resetManagedBean() and session.invalidate() as displayed in Code Snippet -3.
resetManagedBean() method helps us to remove the managed bean based on the bean name, in our case “UserRegistration” is the bean .



This ends our current topic of discussion . I hope it will help you in some way or the other.
Stay tuned for the upcoming topic “Passing Parameters in faces-config.xml”.


No comments:

Post a Comment