Session Management

How to Manage Session?

HTTP is state less protocol, so after response to a client, the server forget all the information of the client. This is sometimes useful but sometimes we need to keep the state of the client and server during an entire period of time i.e. during an entire session. This can be manged by the Http Session. We can managed the session by several ways like using Cookie,using time stamp etc.


Servlet Code to handle a session
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class setSession extends HttpServlet
{
public void doGet(HttpRequest request,HttpResponse response) throws
ServletException,IoException
{
PrintWriter out=response.getWriter();
response.setContentType(“text/html”);
HttpSession session=request.getSession();
if(session.isNew())
out.println(“Welcome!”);
else
out.println(“Welcome Back!”);
}

}

 

Actually using session the server creates a particular session ID for each user.And using the getSession() method it checks whether the session exists. If the session doesn’t exists it creates a new session and paste it on the client machine. The client in turn requests to the server using this session ID.

if We call getSession(false), then it returns preexisting session. If the session doesn’t exist it returns NULL.

To handle Cookie Click here.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.