Open In App

Servlet – Login Form

Improve
Improve
Like Article
Like
Save
Share
Report

Using Java, we can prepare elegant web pages that serve the purpose of registering/logging in to the application, and upon authorized authenticated credentials, the rest of the application screens can be seen. Hence it is much essential to have a login form to accept the inputs from users and then validate the data. For validating the data, we can use javascript at the client-side. i.e. like validating mandatory inputs (username is required/password is required) /if the username is of email pattern then need to validate whether entered text satisfies the email pattern etc., 

Once client-side validations are over, entered credentials are checked against the database stored data. This process can be done only on the server-side. That means those kinds of validations need to be sent as a request to the server and the code needs to be written in Servlet. Usually, as login form credentials are sensitive and should be hidden while passing, it has to get sent as a POST method. In this article, let us see we can design a basic login form and do processing via a servlet. Let us see the required pages to fulfill this feature

login.jsp file:

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
 
<!-- css related code which we can have either in
     same jsp or separately also in a css file -->
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
 
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
 
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}
 
button:hover {
  opacity: 0.8;
}
 
.cancelbutton {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}
 
.container {
  padding: 16px;
}
 
span.psw {
  float: right;
  padding-top: 16px;
}
 
/* Change styles for span and cancel button
   on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbutton {
     width: 100%;
  }
}
</style>
   
<!-- End of css related code which we can have either in
     same jsp or separately also in a css file -->
 
<!-- Client side validations that need to be handled in javascript,
      it can be handled in separate file or in same jsp -->
<script type="text/javascript">
function ValidateEmail(emailId)
{
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(emailId.value.match(mailformat))
    {
        document.getElementById('password').focus();
        return true;
    }
    else
    {
        alert("You have entered an invalid email address!");
        document.getElementById('emailId').focus();
        return false;
    }
}
</script>
 
<!-- End of client side validations that need to be handled
     in javascript, it can be handled in separate file or in same jsp -->
</head>
<body>
 
    <!-- We should have a servlet in order to process the form in
          server side and proceed further -->
    <form action="loginServlet" method="post" onclick="ValidateEmail(document.getElementById('emailId'))">
         <div class="container">
    <label for="username"><b>Email</b></label>
    <input type="text" placeholder="Please enter your email" name="emailId" id = "emailId" required>
 
    <label for="password"><b>Password</b></label>
    <input type="password" placeholder="Please enter Password" name="password" id="password" required>
         
    <button type="submit">Login</button>
    <label>
      <input type="checkbox" checked="checked" name="rememberme"> Remember me
    </label>
  </div>
 
  <div class="container" style="background-color:#f1f1f1">
    <button type="button" class="cancelbutton">Cancel</button>
    <span class="psw">Forgot <a href="<%=request.getContextPath()%>/forgotpassword.jsp">password?</a></span>
  </div>
    </form>
</body>
</html>


Output:

Client-side validation output:

Upon successful client-side validation and server-side validation, the below screen can be seen

In order to perform the above steps, we need to have a servlet and let us have that as LoginServlet.java

Java




import java.io.IOException;
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("/loginServlet")
public class LoginServlet extends HttpServlet {
   
    private static final long serialVersionUID = 1L;      
   
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
   
    // From login.jsp, as a post method only the credentials are passed
    // Hence the parameters should match both in jsp and servlet and
      // then only values are retrieved properly
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // We can able to get the form data by means of the below ways.
        // Form arguments should be matched and then only they are recognised
        // login.jsp component names should match and then only
          // by using request.getParameter, it is matched
        String emailId = request.getParameter("emailId");
        String password = request.getParameter("password");
        // To verify whether entered data is printing correctly or not
        System.out.println("emailId.." + emailId);
        System.out.println("password.." + password);
        // Here the business validations goes. As a sample,
          // we can check against a hardcoded value or pass
          // the values into a database which can be available in local/remote  db
        // For easier way, let us check against a hardcoded value
        if (emailId != null && emailId.equalsIgnoreCase("admin@gmail.com") && password != null && password.equalsIgnoreCase("admin")) {
            // We can redirect the page to a welcome page
            // Need to pass the values in session in order
              // to carry forward that one to next pages
            HttpSession httpSession = request.getSession();
            // By setting the variable in session, it can be forwarded
            httpSession.setAttribute("emailId", emailId);
            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
    }
}


welcome.jsp file:

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
Welcome <%=session.getAttribute("emailId") %>
</body>
</html>


 
In a few cases, we may forget a password, and hence there should be provisions available to do that. We should have a forgotpassword.jsp to achieve that

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}
 
input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
 
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}
 
button:hover {
  opacity: 0.8;
}
 
.cancelbutton {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}
 
.container {
  padding: 16px;
}
 
span.psw {
  float: right;
  padding-top: 16px;
}
 
/* Change styles for span and cancel
   button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbutton {
     width: 100%;
  }
}
</style>
</head>
</head>
<body>
 
    <form action="forgotpassword" method="post">
        <div class="container">
          <label for="username"><b>Enter your email in order to check in our records</b></label>
          <input type="text" placeholder="Please enter email" name="emailId" required>
 
          <button type="submit">Search</button>
         </div
    </form>
</body>
</html>


 
Output: 

Video Explanation  

 



Last Updated : 28 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads