Login and Logout Example in Servlet

In the previous article, we have seen Registration and Login Example in Servlet. In this article, we will see the Log-in and Logout Example using HttpSession in Servlet and we have seen earlier what is HttpSession if you don’t know about it you can go to that article.

Login and Logout Example in Servlet

  • In this example, We will be creating three links for Login, Logout, and View profile.
  • if we click on Log out it should not allow us to view the profile.
  • I have used a hardcoded username and password but you can use the database to compare the login credentials with username=”Nicolas” and password=”1234″.
  • When a user enters the login credentials the request is sent to LoginServlet and it will show a “welcome” message otherwise it will be on the same page login.html.
  • LogoutServlet invalidates the session to logout the user and shows a “Successfully Logout” message.
  • ViewProfile link will be sent the request to ViewServlet and display the message “Welcome to Profile”.

First, create a project structure as shown below

Create a view first – home.htmllink.html, and login.html

home.html

The home.html page will display all the links.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#98FB98">
<h1>Login & Logout Example</h1>
<a href="login.html">Login</a>
<a href="ViewServlet">View Profile</a>
<a href="LogoutServlet">Logout</a>
</body>
</html>

link.html

The link.html will be available on every page.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#98FB98">
  <strong><a href="login.html">Login</a></strong>
  <strong><a href="ViewServlet">View Profile</a></strong>
  <strong><a href="LogoutServlet">Logout</a></strong>
</body>
</html>

login.html

This login.html page displays the login form.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body background="images/img.jpg">
  <form action="LoginServlet" method="post">
    <h1 align="center">Login Page</h1>
    <table align="center">
      <tr>
        <td>Username</td>
        <td><input type="text" name="uname"></td>
      </tr>
      <tr>
        <td>Password</td>
        <td><input type="password" name="pass"></td>
      </tr>
      <tr>
        <td></td>
        <td><input type="submit" value="Login" id="button-1" /></td>
      </tr>
    </table>
  </form>
</body>
</html>

Create the following servlet

  • LoginServlet.java
  • LogoutServlet.java
  • ViewServlet.java

LoginServlet.java

package com.code.Servlet;

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;

public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public LoginServlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter printWriter = response.getWriter();
    RequestDispatcher dispatcher = request.getRequestDispatcher("link.html");
    dispatcher.include(request, response);
    String username = request.getParameter("uname");
    String password = request.getParameter("pass");
    if (username.equals("Nicolas") && password.equals("1234")) {
      System.out.println("in :");
      printWriter.println("<br><h1>Welcome " + username + "</h1>");
      HttpSession httpSession = request.getSession();
      httpSession.setAttribute("username", username);
    } else {
      System.out.println("error");
      printWriter.println("Incorrect Credentials!!!");
      RequestDispatcher dispatcher1 = request.getRequestDispatcher("login.html");
      dispatcher1.include(request, response);
    }
  }

}

LogoutServlet.java

package com.code.Servlet;

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;

public class LogoutServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public LogoutServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter printWriter = response.getWriter();
    RequestDispatcher dispatcher = request.getRequestDispatcher("link.html");
    dispatcher.include(request, response);

    HttpSession httpSession = request.getSession();
    httpSession.invalidate();
    printWriter.println("<h1>Successfully Log out :-)</h1>");
  }

}

ViewServlet.java

package com.code.Servlet;

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;

public class ViewServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public ViewServlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter printWriter = response.getWriter();
    RequestDispatcher dispatcher = request.getRequestDispatcher("link.html");
    dispatcher.include(request, response);
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
      String uname = (String) httpSession.getAttribute("username");
      printWriter.println("<h1>Welcome " + uname + " to your profile!!!</h1>");
    } else {
      printWriter.println("<br><h1>Please Login First</h1>");
      RequestDispatcher dispatcher1 = request.getRequestDispatcher("login.html");
      dispatcher1.include(request, response);
    }

  }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  id="WebApp_ID" version="3.0">
  <display-name>LoginandLogout_Example</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.code.Servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>ViewServlet</servlet-name>
    <servlet-class>com.code.Servlet.ViewServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ViewServlet</servlet-name>
    <url-pattern>/ViewServlet</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.code.Servlet.LogoutServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
  </servlet-mapping>
</web-app>

Run the code on Server and you will get the following output

If I click on View Profile Once again We should get the Error.

Thus this is how we create Log in & Log out using Servlet