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 :

SessionId.java

import java.io.IOException;
import java.io.PrintWriter;
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
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
HttpSession ssn = req.getSession();
if(ssn != null){
pw.println("Your session Id is : ");
String ssnId = ssn.getId();
pw.println(ssnId);
}
else
{
pw.println("Your session is not created yet");
}
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SessionId</display-name>
<servlet>
<servlet-name>SessionId</servlet-name>
<servlet-class>SessionId</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionId</servlet-name>
<url-pattern>/SessionId</url-pattern>
</servlet-mapping>
</web-app>

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