Thursday, 9 May 2013

Setting and getting variables in a session

Data can be sent from

1. JSP to JSP
2. JSP to Servlet (or to an Action Class)
3. Servlet(or from an Action Class) to JSP
4. Servlet to Servlet (Action Class to other)

data can be either sent or retrieved in two ways

1. through Request and Response
2. through Session

here i am gonna demonstrate how to set and get variables through a session

to set a data in a session use the code below

HttpSession ses=request.getSession();
ses.setAttribute( "name", "websitejava.blogspot.com");  

here "name" is the identifier which can be any String and the "websitejava.blogspot.com"  is the actual data contained in the identifier "name".

to get data from a session use the code below

HttpSession ses=request.getSession();
ses.getAttribute( "name");

note that as in example above the getAttribute returns the data as Object, so it has to be converted to String or other respective formats before using it.

for info on how to create sessions follow this link

No comments:

Post a Comment