Checking the Session Existence

Checking the Session Existence


Posted in : Java Posted on : June 24, 2011 at 7:14 PM Comments : [ 0 ]

In this section we will discuss how can we find that the session is not existed already and create a new session if the session is not existed.

Checking the Session Existence

In this section we will discuss how can we find that the session is not existed already and create a new session if the session is not existed.

In the example given below I overloaded the method getSession(boolean). Here I used the getSession(false) because I did not want to create a new session further I have tested whether the session is null or not. And if there will be not a session then the req.getSession() will create a new session.

Example :

PreSession.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PreSession extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
HttpSession ssn = req.getSession(false);
pw.println("Checking the Session existance<br>");
if (ssn == null) {
pw.println("Session is not available <br> Creating a new session.........");
} else

pw.println("Your session is already created");
}

}

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>preExistedSession</display-name>
<servlet>
<servlet-name>PreSession</servlet-name>
<servlet-class>PreSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PreSession</servlet-name>
<url-pattern>/PreSession</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute the above example you will find the following output.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics