Login Form Servlet + JDBC + MySQL Example

This article is a series of Servlet Tutorial. In this article, we will build a simple Employee login module using Servlet, JDBC, and MySQL database.
Learn complete Servlet at https://www.javaguides.net/p/servlet-tutorial.html
Notice that in this article, we are not using JSP to develop a web application. If you want to use JSP and servlet together then check out below tutorials:
In this example, we will write the JDBC code separate from the Servlet. Servlet file we will be used only for handling HTTP requests and business logic. We use the JDBC API to connect to the MySQL database.
You can download the source code of this article from my GitHub repository. The link has given at end of this article.

What we will build?

We will build a simple Employee login module using Servlet, JDBC, and MySQL database. Here is the login form:

Tools and technologies used

  • IDE - STS/Eclipse Neon.3
  • JDK - 1.8 or later
  • Apache Tomcat - 8.5
  • Servlet - 2.5+
  • MySQL - mysql-connector-java-8.0.13.jar

Development Steps

  1. Create Eclipse Dynamic web project
  2. Add Dependencies
  3. Project Structure
  4. MySQL Database Setup
  5. Create a JavaBean - Login.java
  6. Create a LoginDao.java
  7. Create a login.html
  8. Create a loginsuccess.html
  9. Demo

1. Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:
1. On the main menu select File > New > Project....
2. In the upcoming wizard choose Web > Dynamic Web Project.


3. Click Next.
4. Enter project name as "login-servlet-jdbc-example";
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version. 

2. Add Dependencies

Add the latest release of below jar files to the lib folder.
- servlet-api.2.3.jar
- mysql-connector-java-8.0.13.jar
In Eclipse, paste these JAR files to your project directory: WebContent/WEB-INF/lib

3. Project Structure

Standard project structure for your reference - 

4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Now, create a login table using below DDL script:
CREATE TABLE `login` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Here is an Insert SQL statement:
INSERT INTO `demo`.`login` (`username`, `password`) VALUES ("Ramesh", "Ramesh");

5. Create a JavaBean - LoginBean.java

Let's create an Employee JavaBean class which we will use to create an object and populate registration data in Servlet:
import java.io.Serializable;

public class LoginBean implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1 L;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

6. Create a LoginDao.java

We will separate JDBC accessing code separate from Servlet. So let's create an LoginDao.java class and add following code to it:
package net.javaguides.login.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.javaguides.login.bean.LoginBean;

public class LoginDao {

    public boolean validate(LoginBean loginBean) throws ClassNotFoundException {
        boolean status = false;

        Class.forName("com.mysql.jdbc.Driver");

        try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/demo?useSSL=false", "root", "root");

            // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection
            .prepareStatement("select * from login where username = ? and password = ? ")) {
            preparedStatement.setString(1, loginBean.getUsername());
            preparedStatement.setString(2, loginBean.getPassword());

            System.out.println(preparedStatement);
            ResultSet rs = preparedStatement.executeQuery();
            status = rs.next();

        } catch (SQLException e) {
            // process sql exception
            printSQLException(e);
        }
        return status;
    }

    private void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}

7. Create a login.html

Let's design login HTML form with following fields:
  • username
  • password
<!DOCTYPE html>
<html>

<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
</head>

<body>
    <div align="center">
        <h1>Employee Login Form</h1>
        <form action="login" method="post">
            <table style="with: 100%">
                <tr>
                    <td>UserName</td>
                    <td><input type="text" name="username" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password" /></td>
                </tr>
            </table>
            <input type="submit" value="Submit" />
        </form>
    </div>
</body>
</html>

8. Create a loginsuccess.html

After an employee successfully login then this page shows a successful message on screen:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <div align="center">
  <h1>You have logined successfully</h1>
 </div>
</body>
</html>

9. Demo

It's time to see a demo of the above development. Deploy this web application in tomcat server.

Employee Login Form

Once you deploy this application successfully then hit this link into a browser - http://localhost:8080/login-servlet-jdbc-mysql-example/login.html

Employee Login Success Page

Comments