Servlet HttpSession

In this tutorial you will learn about the Servlet HttpSession and its application with practical example.

Servlet HttpSession Interface

This interface provides a way to identify the user. Servlet container uses this interface for the creation of session between HTTP client and HTTP server. HttpSession can perform binding of objects, also it can be view and manipulate information of session.

HttpSession Interface Methods

There are some important methods which are used in this interface.

HttpSession getSession(): This method returns the current session which is associated with this request.

HttpSession getSession(Boolean create): This method returns the current session which is associated with this request when it Boolean value is false, it create new when it is true.

void setAttribute(String name, String value): This method is used to set the attribute in session.

lang.Object getAttribute(String name): This method is used to return the value of given parameter from session.

lang.String getId(): This method is used to returns the string of session unique identifier.

void invalidate(): This method Invalidates this session then unbinds any objects bound to it.

Long getLastAccessedTime(): This method returns the last time the client sent the request associated with this session.

Long getCreationTime(): This method returns the time when this session was created.

Example:-

Let’s understand it by an example.

index.html

This will be our welcome file from which we will send the user name.

FirstSession.java

From this servlet we will store our session from below method.

Check below code for this servlet.

SecondSession.java

From this servlet file we will get the session data with the help of below code.

Recommended:-  Servlet SendRedirect

Check below code of this servlet file.

Output:-

Check output of this code.

Recommended:-  Servlet HttpSession Login Logout

Screen 1:-

image001

Screen 2:-

image003

Screen 3:-

image005

In this tutorial we have learn about the Servlet HttpSession and its application with practical example. I hope you will like this tutorial.