This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Servlets and the fly likes Session in a servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Session in a servlet" Watch "Session in a servlet" New topic

Session in a servlet

amit sanghai
Ranch Hand

Joined: Dec 05, 2000
Posts: 231
What is a session? How do you implement a session in servlets?
Joe Gilvary
Ranch Hand

Joined: May 11, 2001
Posts: 152
A session is shared state information between the
server and the client. You do not have to implement
it in servlets; the container vendor has to implement
it for you.
There is a servlet trail in the Java tutorial
that includes some info on saving state. Check
Also, the current Servlet 2.3 spec discusses sessions,
and what the servlet container must do to support
sessions for the application developer. That spec
is available at
Zkr Ryz
Ranch Hand

Joined: Jan 04, 2001
Posts: 187
Basically sessions are object that allows you to mantain the state of a user between servlets calls.
// the next code excerpt set an attribute in a
// session if there's no userName in the session.
public void doGet( HttpServletRequest request,
HttpServletResponse response )
HttpSession session = request.getSession();
if( session.getAttribute( "userName" ) == null ){
session.setAttribute( "userName","guest");

see the API for more information:
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
a session is a way for us programmers to keep a tab on user sessions. that means that because the http protocol doesnt allow us to know if it is the same user accesing several pages in our web site, we have somethn called a session.
in order to explain this better u need to understand several concepts:
first , every time a user access a page he makes a REQUEST to that page.
we can handle his REQUESTS per each time he access a page.
however we wish to know that even if the user access several pages all in the same SESSION (as in transaction) we have to keep some kind of tab to know thats it the same user in the same transaction.
in order to do that in servlets we can sort of put a cookie in his side letting us know in every page that its the same user(by identifying his cookie). this cookie is made easy to put as in the form of a session.
in servlet we can do:
HttpSession user=request.getSession();
this get the current session for us or creates one if there it is the first page visited.
thats it
I agree. Here's the link:
subject: Session in a servlet
jQuery in Action, 3rd edition