Get Session Id

Ads
 

Get Session Id

In this example we are going to make a program in which we will find the session id which was generated by the container.

In this example we are going to make a program in which we will find the session id which was generated by the container.

Get Session Id

     

In this example we are going to make a program in which we will find the session id which was generated by the container. 

HttpSession session = request.getSession(); Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object. There is no need to generate the unique session id. There is  no need to make a new Cookie object. Everything happens automatically behind the scenes. 

As soon as call the method getSession() of the request object a new object of the session gets created by the container and a unique session id generated to maintain the session. This session id is transmitted back to the response object so that whenever the client makes any request then it should also attach the session id with the requsest object so that the container can identify the session. 

The code of the program is given below:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionIdServlet extends HttpServlet{
  protected void doGet(HttpServletRequest request, HttpServletResponse
    response
)throws ServletException, IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  HttpSession session = request.getSession();
  String id = session.getId();
  pw.println("Session Id is : " + id);
  }
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 <servlet>
 <servlet-name>Zulfiqar</servlet-name>
 <servlet-class>SessionIdServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Zulfiqar</servlet-name>
 <url-pattern>/SessionIdServlet</url-pattern>
 </servlet-mapping>
</web-app>

The output of the program is given below:

Download this example:

Ads

Ads