×

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies that implement session tracking. The main use of session tracking is to maintain the state of the users.

Session Tracking Techniques

There are 4 ways to track the sessions

  • HTTP Session Interface
  • Cookies
  • Hidden from field
  • URL rewriting

1. HTTP Session Interface

In HTTP interface, session id is created by taking the help of container for each user.

The objects which are created in this session can bind the objects and manipulate the session properties.

Methods in HTTP Session Interface

  1. public HttpSession getSession()
    By using this method, we can get the information about current session. If there is no session, then a session will be created.
  2. public String getId()
    By using this method, a string is returned which contains the unique value.
  3. public void invalidate ()
    By using this method, it invalidates the session and unbinds the binded objects to it.
  4. public long getCreationTime()
    By using this method, we will get the time at which session is created and it is measured in milliseconds.
  5. public long getLastAccessedTime()
    By using this method, we will get to know the last time at which session is accessed and it is measured in milliseconds.

Program for servlets using HTTP session interface

index.html

<html>  
<head>  
<body>  
<form action = "servletA">    
UserName: <input type = "text" sername = "userName"/><br/>    
<input type = "submit" value = "Press the Button"/>    
</form>    
</body>  
</html>

ServletEx1.java

import java.io.*;  
import jakarta.servlet.*;  
import jakarta.servlet.http.*;  
public class ServletEx1 extends HttpServlet {  
public void Get(HttpServletRequest req, HttpServletResponse res)  
{  
try {   
String conType = "text/html";  
res.setContentType(conType);    
PrintWriter oa = res.getWriter();  
String sername = req.getParameter("userName");     
oa.println("Welcome to Java" + sername + "!");     
HttpSession httpSes= req.getSession();   
httpSes.setAttribute("uname", sername);  
oa.print("<a href='servletB'> Press Here </a>");
oa.close();  
}  
catch (Exception e)   
{  
System.out.println(e);  
}  
}  
}

ServletEx2.java

import jakarta.servlet.*;  
import jakarta.servlet.http.*;  
import java.io.*;  
public class ServletEx2 extends HttpServlet   
{  
public void doGet(HttpServletRequest req, HttpServletResponse res)  
{  
try   
{  
String conType = "text/html";  
response.setContentType(conType);  
PrintWriter oa = res.getWriter();  
HttpSession se1 = req.getSession(false);  
  
String name = (String)se1.getAttribute("uname");  
// printing the name and message  
oa.print(sername + " you have reached the second page.");  
oa.close();  
}  
catch (Exception e)   
{  
    System.out.println(e);  
}  
}  
}

Web.xml

</textarea></div>  
<p><strong>FileName:</strong> web.xml</p>  
<div class="codeblock"><textarea name="code" class="xml">  
<web-app >    
<servlet >    
<servlet-name > a1 </servlet-name >    
<servlet-class > ServletEx1 </servlet-class >    
</servlet >     
<servlet-mapping >    
<servlet-name > a1 </servlet-name >    
<url-pattern > /servletA </url-pattern >    
</servlet-mapping >     
<servlet >    
<servlet-name > a2 </servlet-name >    
<servlet-class > ServletEx2 </servlet-class >    
</servlet >    
<servlet-mapping >    
<servlet-name > a2 </servlet-name >    
<url-pattern > /servletB </url-pattern >    
</servlet-mapping >    
</web-app >

2.Cookies in Servlet

Cookie consists of small information of multi-client requests. In the cookies approach, we include a cookie with the servlet response. Cookies are therefore kept in the browser's cache. After that, if the user sends a request, a cookie is automatically attached to the request.

Types of Cookies

  1. Non persistent Cookie
    It is valid only for certain amount of time. Each time after the browser is closed, it is removed.
  2. Persistent Cookie
    It is valid for multiple sessions. It is replaced only if the user log out or sign out.

3.URL Rewriting

In this method we will append the previous identifier to next servlet. An approach of adding a session ID to the requested URL is called URL rewriting.

Program for servlets using URL rewriting

index.html

<html>  
<head>  
<body>  
<form action = "servletA">    
UserName: <input type = "text" sername = "userName"/><br/>    
<input type = "submit" value = "Press the Button"/>    
</form>    
</body>  
</html>

ServletEx1.java

import java.io.*;  
import jakarta.servlet.*;  
import jakarta.servlet.http.*;  
public class ServletEx1 extends HttpServlet {  
public void Get(HttpServletRequest req, HttpServletResponse res)  
{  
try {   
String conType = "text/html";  
res.setContentType(conType);    
PrintWriter oa = res.getWriter();  
String sername = req.getParameter("userName");     
oa.println("Welcome to Java" + sername + "!");     
HttpSession httpSes= req.getSession();   
httpSes.setAttribute("uname", sername);  
oa.print("<a href='servletB'> Press Here </a>");
oa.close();  
}  
catch (Exception e)   
{  
System.out.println(e);  
}  
}  
}

ServletEx2.java

import jakarta.servlet.*;  
import jakarta.servlet.http.*;  
import java.io.*;  
public class ServletEx2 extends HttpServlet   
{  
public void doGet(HttpServletRequest req, HttpServletResponse res)  
{  
try   
{  
String conType = "text/html";  
response.setContentType(conType);  
PrintWriter oa = res.getWriter();  
HttpSession se1 = req.getSession(false);  
  
String name = (String)se1.getAttribute("uname");  
// printing the name and message  
oa.print(sername + " you have reached the second page.");  
oa.close();  
}  
catch (Exception e)   
{  
    System.out.println(e);  
}  
}  
}

Web.xml

</textarea></div>  
<p><strong>FileName:</strong> web.xml</p>  
<div class="codeblock"><textarea name="code" class="xml">  
<web-app >    
<servlet >    
<servlet-name > a1 </servlet-name >    
<servlet-class > ServletEx1 </servlet-class >    
</servlet >     
<servlet-mapping >    
<servlet-name > a1 </servlet-name >    
<url-pattern > /servletA </url-pattern >    
</servlet-mapping >     
<servlet >    
<servlet-name > a2 </servlet-name >    
<servlet-class > ServletEx2 </servlet-class >    
</servlet >    
<servlet-mapping >    
<servlet-name > a2 </servlet-name >    
<url-pattern > /servletB </url-pattern >    
</servlet-mapping >    
</web-app >

4.Hidden from field

In the case of a hidden form field, a hidden textfield is utilised to keep track of a user's status.

In this instance, the data is obtained from another servlet and stored in the hidden field. This strategy is preferable if we need to submit forms on each page and don't want to rely on the browser.


Related Topics

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.