session id in servlet Example

session id in servlet Example

Posted in : Java Posted on : June 27, 2011 at 6:37 PM Comments : [ 0 ]

In this section we will discuss about how can we get a session id in servlet.

session id in servlet Example

In this section we will discuss about how can we get a session id in servlet.

In the example given below I created a HttpSession object (ssn) to request for getting the session and much more work. All the works, like generating a unique random sessionId, creation of an object of Cookie etc. is happened automatically. As the calling of getSession method by the object of HttpServletRequest (req), container creates a new session and generates an unique and random sessionId to maintain the session.

Example :

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionId extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
PrintWriter pw = res.getWriter();
HttpSession ssn = req.getSession();
if(ssn != null){
pw.println("Your session Id is : ");
String ssnId = ssn.getId();
pw.println("Your session is not created yet");


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" 

Output :

when you will execute the above example you will find the output as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics