×

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

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.