Servlet – HttpSession Login and Logout Example

13 Jan, 2022
In general, the term “Session” in computing language, refers to a period of time in which a user’s activity happens on a website. Whenever you login to an application or a website, the server should validate/identify the user and track the user interactions across the application. To achieve this, Java Web Server supports the servlet standard session interface, called HttpSession, to perform all the session-related activities.
Java servlets has HttpSession(I) in javax.servlet.http package. This interface provides a way to identify a user across more than one-page requests or visit a Website. Servlet container uses this interface to create a session between an HTTP client and an HTTP server and stores information about that user. It provides various methods to manipulate information about a session such as,
To bind a session object with a specified user.
To get the creation time.
To know the last time, the user had accessed the website in that session.
To invalidate the session etc.
Once the user login to the website, we need to create a new session. To do this, we need to use getSession() method in HttpServletRequest Interface.
1) HttpSession getSession():
Java
HttpSession session = request.getSession();
This method returns the current session associated with this request. If the request does not have a session, it creates one. We can also create a session using  getSession(boolean create) method in HttpServletRequest Interface.
2) HttpSession getSession(boolean create):
We can pass the boolean parameters – true or false.
getSession(true):
Java
HttpSession session = request.getSession(true);
This method is the same as getSession(), where it returns the current session associated with this request. If the request does not have a session, it creates one.
getSession(false):
Java
HttpSession session = request.getSession(false);
This method returns the current session associated with this request. If the request does not have a session, it returns null.
Once the user requests to logout, we need to destroy that session. To do this, we need to use invalidate() method in HttpSession Interface.
void invalidate():
Java
HttpSession session = request.getSession();session.invalidate();
When this invalidate method is called on the session, it removes all the objects that are bound to that session.
We will create a basic Servlet program to display a welcome message for the validated users.
Steps to create the program:
Create “Dynamic Web Project – Servlet_LoginLogout” in Eclipse.
Under WEB-INF folder, create a JSP page – “login.jsp” to get the login credentials of the user.
Under src folder, create a Servlet – “LoginServlet.java” to process the login request and generate the response.
Under WEB-INF folder, create a JSP page – “welcome.jsp” to display the welcome message to the user.
Under src folder, create a Servlet – “LogoutServlet” to process the logout request and generate the response.
Run the program using “Run As -> Run on Server”.
Project Structure
login.jsp
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Login Page</title></head><body>      <form action="login" method="post">          <h3>Enter Login details</h3>          <table>            <tr>                <td>User Name:</td>                <td><input type="text" name="usName" /></td>            </tr>            <tr>                <td>User Password:</td>                <td><input type="password" name="usPass" /></td>            </tr>          </table>                  <input type="submit" value="Login" />      </form></body></html>
In “login.jsp”, we have 2 fields, User Name, and Password.
User Name input type is specified as “text”, which means text field.
Password field input type is specified as “password” so that when the user enters the password field, it hides the letters as dots.
We have formed with action “login” and method “post” so that when this form is submitted, it maps with the LoginServlet which is having the same URL mapping, and executes the “doPost” method of that servlet.
LoginServlet.java:
Java
import java.io.IOException;import java.io.PrintWriter;  import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;  @WebServlet("/login")public class LoginServlet extends HttpServlet {    private static final long serialVersionUID = 1L;      public LoginServlet() {        super();    }      // doPost() method    protected void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {          // Set the content type of response to "text/html"        response.setContentType("text/html");          // Get the print writer object to write into the response        PrintWriter out = response.getWriter();          // Get the session object        HttpSession session = request.getSession();          // Get User entered details from the request using request parameter.        String user = request.getParameter("usName");        String password = request.getParameter("usPass");          // Validate the password - If password is correct,         // set the user in this session        // and redirect to welcome page        if (password.equals("geek")) {            session.setAttribute("user", user);            response.sendRedirect("welcome.jsp?name=" + user);        }        // If the password is wrong, display the error message on the login page.        else {            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");            out.println("<font color=red>Password is wrong.</font>");            rd.include(request, response);        }        // Close the print writer object.        out.close();    }}
In “LoginServlet.java”, we are using annotation “@WebServlet(“/login”)” to map the URL request. You can also specify this mapping for the servlet using Deployment descriptor – web.xml.
As we learned, get the session object of HttpSession. If the request does not have a session, it creates a session and returns it.
Here, we need to get the user details that are passed through the request, Name, and Password using “getParameter()” on the request object.
For simplicity, we are just validating the password field. So, the User name can be anything but the Password must be”geek”.
Validate the password and if it is correct, set this attribute value in session and redirect the page to display the welcome message.
If the entered password is incorrect, display an error message to the user in the login screen using the Print writer object.
welcome.jsp:
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Welcome Page</title></head><body>      <form action="logout" method="get">          <h2>            Hello            <%=request.getParameter("name")%>!        </h2>        <h3>Welcome to GeeksforGeeks..</h3>          <br> <input type="submit" value="Logout" />    </form>      </body></html>
On the Welcome page, display the user name and a welcome message.
We have a form with action “logout” and method “get” so that when this form is submitted, it maps with the LogotServlet which is having the same URL mapping, and executes the “doGet” method of that servlet.
LogoutServlet.java:
Java
import java.io.IOException;import java.io.PrintWriter;  import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;  @WebServlet("/logout")public class LogoutServlet extends HttpServlet {    private static final long serialVersionUID = 1L;      public LogoutServlet() {        super();    }      // doGet() method    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {          // Get the print writer object to write into the response        PrintWriter out = response.getWriter();          // Set the content type of response to "text/html"        response.setContentType("text/html");          // For understanding purpose, print the session object in the console before        // invalidating the session.        System.out.println("Session before invalidate: "+ request.getSession(false));          // Invalidate the session.        request.getSession(false).invalidate();          // Print the session object in the console after invalidating the session.        System.out.println("Session after invalidate: "+ request.getSession(false));          // Print success message to the user and close the print writer object.        out.println("Thank you! You are successfully logged out.");        out.close();    }  }
Here also, we are using the annotation “@WebServlet(“/logout”)” to map the URL request.
When the user clicks on Logout, we need to destroy that session. So, call the “invalidate()” method on that session object.
For our understanding, we can print the session object value in the console to see if the session is invalidated.
As we learned, “getSession(false)” returns the current session on request if it exists, if not it returns null. So, after invalidating the session, it should print null in the console.
Finally, print the success message to the user.
Output:
Run the program on the server.
URL: http://localhost:8081/Servlet_LoginLogout/login.jsp
Login Page
The browser displays the Login page.
Login with User details
Enter the user name and password and click on Login.
Give the Password as “geek” as we are validating against it, if not it throws an error like below.
Incorrect_password
Enter the correct credentials and log in.
Welcome Page
The User name which we set in the session object is displayed with a welcome message.
Click on Logout.
Logout_success
Now, if you check the console, it prints the session object values.
Console
As you can see, “getSession()” returned the existing session object.
After the invalidate method, as there is no session, it returned “null”.
1) In the above example, we have used the “invalidate()” method, you can also use the “removeAttribute(String name)” method in HttpSession Interface.
Java
HttpSession session = request.getSession();session.removeAttribute("user");
This method removes the object bound with the specified name, in this example – “user” from this session. If the session does not have an object bound with the specified name, it does nothing. So, instead of the “invalidate()” method, you can use the “removeAttribute(String)” to logout the user from the session.
2) In the above example, we invalidated the session manually. If you want, you can also specify the session for time out automatically after being inactive for a defined time period.
“void setMaxInactiveInterval(int interval)”:
Java
HttpSession session = request.getSession();session.setMaxInactiveInterval(100);
This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. Here, as we specified the value “100”, the session will be invalidated after 100 seconds of inactive time from the user. Servlet container will destroy the session after 100 seconds of inactive – Session timeout.
In this way, you can maintain a session for a specific user/client and can implement Login and Logout for applications using HttpSession Interface methods based on the requirements.
java-servlet
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java