Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Everything You Need To Know About Session In Java?

Last updated on Jun 17,2021 25.7K Views

12 / 22 Blog from Advance Java

This will introduce you to a topic called as Session In Java and in process brief you on how Session management works in Java. Following pointers will be covered in this article,

So let us get started then,

Session In Java

The time interval in which two systems(i.e. the client and the server) communicate with each other can be termed as a session. In simpler terms, a session is a state consisting of several requests and response between the client and the server.

It is a known fact that HTTP and Web Servers are both stateless. Hence, the only way to maintain the state of the user is by making use of technologies that implement session tracking.
Session tracking in servlets can be implemented by a number of methods, cookies being one of them. However, they have multiple disadvantages:

  • Only textual information can be kept by them.
  • If cookies are disabled by a user, the web application is unable to make use of them.
  • Not more than 4kb of data can be contained by a single cookie.
  • Another way to implement session tracking is by creating sessions with unique session ids for every user in a java servlet.

Moving on with this article on Session in Java

Http Session Interface

Servlets in java provide an interface known as ‘HttpSessionInterface’.
They consist of various methods, some of which are discussed below:

  • public HttpSession getSession(boolean create): This method gets the session associated with the request. In case it is not available or not present, a new session is created which is based upon the Boolean argument specified.
  • public String getId(): The unique session id is returned by this method.
  • public long getCreationTime(): The time when the session was created is returned by this method. It is measured in milliseconds.
  • public long getLastAccessedTime(): The time when the session was last accessed is returned by this method. It is measured in milliseconds.
  • public void invalidate(): A session can be invalidated by using this method.

Example:
In the example given below, we have made use of the getAttribute() and setAttribute() method of the HttpSession interface.

Moving on with first example in this Session In Java article

index.html

<form action="loginform">
User Name:<input type="text" name="userName"/>
Password:<input type="password" name="userPassword"/>
<input type="submit" value="submit"/>
</form>

Moving on with second example

Servlet1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Welcome "+name);
pwriter.print("Here is your password: "+password);
HttpSession session=request.getSession();
session.setAttribute("usname",name);
session.setAttribute("uspass",password);
pwriter.print("<a href='Welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}

Moving on with third example

Servlet2.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("usname");
String myPass=(String)session.getAttribute("uspass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}

Moving on with fourth example in this Session In Java article

web.xml

<web-app>
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet1</servlet-name>
<url-pattern>/loginform</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>

There are various advantages and disadvantages of this interface as listed out below:

Session In Java

Advantages:

  • All kinds of objects, such as database and text can be stored into a session.
  • Sessions are secure.

Moving on with Disadvantages

Disadvantages:

  • Since the session object is stored on a server, there is performance overhead.
  • Serialization and de-serialization also lead to overhead.

It is highly advantageous to use the HttpSessionInterface to achieve session tracking.

Thus we have come to an end of this article on ‘Session In Java’. If you wish to learn more, check out the Java Certification Course by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Everything You Need To Know About Session In Java?

edureka.co