JSP Registration Form + JDBC + MySQL Example

In this tutorial, we will create a JSP Registration Form that connects to a MySQL database using JDBC. We'll use the latest versions of JSP and Servlet and follow a structured approach.

Step 1: Setting Up the Development Environment

Ensure you have the following tools installed:

  1. JDK (Java Development Kit) - preferably the latest version.
  2. Apache Tomcat - latest version.
  3. MySQL - latest version.
  4. IDE (Integrated Development Environment) - Eclipse, IntelliJ IDEA, or any other Java IDE.
  5. Maven - for managing project dependencies.

Step 2: Create a Maven Project

  1. Open your IDE and create a new Maven project.
  2. Update the pom.xml file to include the necessary dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://www.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>registration-webapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jakarta.servlet.jsp</groupId>
            <artifactId>jakarta.servlet.jsp-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jakarta.servlet.jsp.jstl</groupId>
            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.1</version>
            </plugin>
        </plugins>
    </build>
</project>

Step 3: Directory Structure

Ensure your project structure looks like this:

registration-webapp/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           ├── controller/
│   │   │           │   ├── RegistrationServlet.java
│   │   │           ├── dao/
│   │   │           │   ├── UserDAO.java
│   │   │           ├── model/
│   │   │           │   └── User.java
│   │   │           └── util/
│   │   │               └── DBUtil.java
│   │   ├── resources/
│   │   └── webapp/
│   │       ├── WEB-INF/
│   │       │   └── lib/
│   │       ├── index.jsp
│   │       ├── registration.jsp
│   │       └── success.jsp
└── pom.xml

Step 4: Create the Database

Create a MySQL database and a users table.

CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL
);

Step 5: Create Model Class

Create a model class User.java in the com.example.model package.

package com.example.model;

public class User {
    private int id;
    private String username;
    private String password;
    private String email;

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Step 6: Create DAO Class

Create a DAO class UserDAO.java in the com.example.dao package.

package com.example.dao;

import com.example.model.User;
import com.example.util.DBUtil;

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

public class UserDAO {
    public int registerUser(User user) throws ClassNotFoundException {
        String INSERT_USERS_SQL = "INSERT INTO users" +
            "  (username, password, email) VALUES " +
            " (?, ?, ?);";

        int result = 0;

        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getEmail());

            System.out.println(preparedStatement);
            result = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}

Step 7: Create Utility Class

Create a utility class DBUtil.java in the com.example.util package.

package com.example.util;

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

public class DBUtil {
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/userdb";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "root";

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    }
}

Step 8: Create Controller Class

Create a controller class RegistrationServlet.java in the com.example.controller package.

package com.example.controller;

import com.example.dao.UserDAO;
import com.example.model.User;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegistrationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserDAO userDAO;

    public void init() {
        userDAO = new UserDAO();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);

        try {
            int result = userDAO.registerUser(user);
            if (result == 1) {
                request.setAttribute("NOTIFICATION", "User Registered Successfully!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
        dispatcher.forward(request, response);
    }
}

Step 9: Create JSP Pages

Create a registration form registration.jsp in the src/main/webapp directory.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Registration Form</title>
</head>
<body>
    <h2>Registration Form</h2>
    <form action="register" method="post">
        <label>Username:</label>
        <input type="text" name="username" required><br><br>
        <label>Password:</label>
        <input type="password" name="password" required><br><br>
        <label>Email:</label>
        <input type="email" name="email" required><br><br>
        <input type="submit" value="Register">
    </form>
</body>
</html>

Create a success page success.jsp in the src/main/webapp directory.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Registration Successful</title>
</head>
<body>
    <h2>${

NOTIFICATION}</h2>
    <a href="registration.jsp">Register Another User</a>
</body>
</html>

Step 10: Run the Application

  1. Build the Maven project using mvn clean install.
  2. Deploy the registration-webapp.war file to Apache Tomcat.
  3. Start the Tomcat server and navigate to http://localhost:8080/registration-webapp/registration.jsp.

You should see the registration form. Upon submitting the form, the user details will be saved in the MySQL database, and you'll be redirected to the success page.

Conclusion

In this tutorial, we created a JSP Registration Form that connects to a MySQL database using JDBC. We used the latest versions of JSP and Servlet, and we followed a structured approach to create a simple yet functional registration application.

Comments

  1. Sorry I have some problem when I try to add an image to account and store it in DataBase. Do you have a tutorial when explain an example like this? Thanks a lot in advatage :)

    ReplyDelete
  2. how can i add another row on the same table please , i have tried to use autoincrement in ID column but still getting an error that java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'employee.PRIMARY'

    ReplyDelete
    Replies
    1. You need to add AUTO_INCREMENT to id column in the table. Check updated SQL script in this tutorial.

      Delete

Post a Comment

Leave Comment