What will we build?
Development Steps
- Create an Eclipse Dynamic Web Project
- Add Dependencies
- Project Structure
- MySQL Database Setup
- Create a JavaBean -
Employee.java
- Create an
EmployeeDao.java
- Create an
EmployeeServlet.java
- Create
employeeregister.jsp
- Create
employeedetails.jsp
- Demo
Step 1: Create an Eclipse Dynamic Web Project
To create a new dynamic Web project in Eclipse:
- On the main menu, select
File > New > Project...
. - In the upcoming wizard, choose
Web > Dynamic Web Project
. - Click
Next
. - Enter the project name as
jsp-servlet-jdbc-mysql-example
. - Ensure that the target runtime is set to Apache Tomcat with the currently supported version.
Step 2: Add Dependencies
Add the latest release of the below JAR files to the lib
folder:
jakarta.servlet-api-6.1.0.jar
mysql-connector-java-8.0.13.jar
jakarta.servlet.jsp.jstl-api-3.0.0.jar
If you are using a Maven project then add the following dependencies to your pom.xml
:
<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://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.javaguides.servlet.tutorial</groupId>
<artifactId>java-servlet-tutorial</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>java-servlet-tutorial Maven Webapp</name>
<url>http://maven.apache.org</url>
<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.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>
<build>
<finalName>java-servlet-tutorial</finalName>
</build>
</project>
Explanation:
- This
pom.xml
file defines the project dependencies and build configuration. - The
jakarta.servlet-api
dependency is for using the latest servlet API. - The
jakarta.servlet.jsp.jstl-api
dependency is for using JSP standard tag library. - The
mysql-connector-java
dependency is for connecting to the MySQL database.
Step 3: Project Structure
Here is the standard project structure for your reference:
Explanation:
- The
src/main/java
directory contains the Java source files. - The
src/main/webapp
directory contains the web application files (JSP pages). - The
pom.xml
file is the Maven project file.
Step 4: MySQL Database Setup
Create a database named employees
in MySQL and then create an employee
table using the following DDL script:
CREATE TABLE `employee` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`first_name` varchar(20) DEFAULT NULL,
`last_name` varchar(20) DEFAULT NULL,
`username` varchar(250) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`contact` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Explanation:
- The
employee
table has columns forid
,first_name
,last_name
,username
,password
,address
, andcontact
. - The
id
column is the primary key and is auto-incremented.
Step 5: Create a JavaBean - Employee.java
package net.javaguides.jsp.jdbc.bean;
import java.io.Serializable;
/**
* JavaBean class used in jsp action tags.
* @author Ramesh Fadatare
*/
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
private String username;
private String password;
private String address;
private String contact;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
}
Explanation:
- The
Employee
class is a JavaBean that represents the employee data. - It implements
Serializable
to allow the bean to be persisted. - It has getter and setter methods for all fields.
Step 6: Create EmployeeDao.java
package net.javaguides.jsp.jdbc.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import net.javaguides.jsp.jdbc.bean.Employee;
public class EmployeeDao {
public int registerEmployee(Employee employee) throws ClassNotFoundException {
String INSERT_USERS_SQL = "INSERT INTO employee" +
" (first_name, last_name, username, password, address, contact) VALUES " +
" (?, ?, ?, ?, ?,?);";
int result = 0;
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/employees?useSSL=false", "root", "root");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, employee.getFirstName());
preparedStatement.setString(2, employee.getLastName());
preparedStatement.setString(3, employee.getUsername());
preparedStatement.setString(4, employee.getPassword());
preparedStatement.setString(5, employee.getAddress());
preparedStatement.setString(6, employee.getContact());
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
result = preparedStatement.executeUpdate();
} catch (SQLException e) {
// process sql exception
printSQLException(e);
}
return result;
}
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();
}
}
}
}
}
Explanation:
- The
EmployeeDao
class handles database operations related to employee registration. - The
registerEmployee
method inserts a new employee into the database. - It uses a
PreparedStatement
to prevent SQL injection. - The
printSQLException
method prints detailed SQL exceptions.
Step 7: Create EmployeeServlet.java
package net.javaguides.jsp.jdbc.web;
import java.io.IOException;
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 net
.javaguides.jsp.jdbc.database.EmployeeDao;
import net.javaguides.jsp.jdbc.bean.Employee;
@WebServlet("/register")
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private EmployeeDao employeeDao;
public void init() {
employeeDao = new EmployeeDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String contact = request.getParameter("contact");
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastName);
employee.setUsername(username);
employee.setPassword(password);
employee.setContact(contact);
employee.setAddress(address);
try {
employeeDao.registerEmployee(employee);
} catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("employeedetails.jsp");
}
}
Explanation:
- The
EmployeeServlet
class processes the HTTP request for employee registration. - It uses the
EmployeeDao
to save the employee data into the database. - If registration is successful, it redirects to
employeedetails.jsp
.
Step 8: Create employeeregister.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Registration Form</title>
</head>
<body>
<div align="center">
<h1>Employee Register Form</h1>
<form action="<%= request.getContextPath() %>/register" method="post">
<table style="width: 80%">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>UserName</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" /></td>
</tr>
<tr>
<td>Contact No</td>
<td><input type="text" name="contact" /></td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
Explanation:
- This JSP file creates an employee registration form.
- The form fields are
firstName
,lastName
,username
,password
,address
, andcontact
. - The form's action attribute points to the
/register
URL, which maps to theEmployeeServlet
.
Step 9: Create employeedetails.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Employee Details</title>
</head>
<body>
<h1>User successfully registered!</h1>
</body>
</html>
Explanation:
- This JSP file displays a success message when an employee is successfully registered.
Step 10: Demo
It's time to see a demo of the above development. Deploy this web application in Tomcat server.
Employee Registration Form
Once you deploy this application successfully, navigate to http://localhost:8080/jsp-servlet-jdbc-mysql-example/employeeregister.jsp
to see the registration form:
Registration Success Page
After entering the employee details and submitting the form, if registration is successful, you will be redirected to employeedetails.jsp
:
Conclusion
In this tutorial, we learned how to build a simple employee registration module using JSP, Servlet, JDBC, and MySQL databases. By following the steps above, you can create a similar web application for your own use.
Related Servlet Posts
- What is a Servlet in Java?
- Servlet Life Cycle
- Servlet Interface Example
- GenericServlet Class Example
- HttpServlet Class Example Tutorial
- HttpServlet doGet() Method Example
- HttpServlet doPost() Method Example
- @WebServlet Annotation Example
- @WebInitParam Annotation Example
- @WebListener Annotation Example
- @WebFilter Annotation Example
- @MultipartConfig Annotation Example
- How to Return a JSON Response from a Java Servlet
- Servlet Registration Form + JDBC + MySQL Database Example
- Login Form Servlet + JDBC + MySQL Example
- Servlet JDBC Eclipse Example Tutorial
- JSP Servlet JDBC MySQL CRUD Example Tutorial
- Servlet + JSP + JDBC + MySQL Example
- Registration Form using JSP + Servlet + JDBC + Mysql Example
- Login Form using JSP + Servlet + JDBC + MySQL Example
- JSP Servlet Hibernate CRUD Example
- JSP Servlet Hibernate Web Application
- Hibernate Registration Form Example with JSP, Servlet, MySQL
- Login Form using JSP + Servlet + Hibernate + MySQL Example
Project is running but data are not stored in database
ReplyDeleteThe data is stored on the database. The table should be created like this. AUTO_INCREMENT should be used for the id.
DeleteCREATE TABLE employee
(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
username VARCHAR(250) NOT NULL,
PASSWORD VARCHAR(250) NOT NULL,
address VARCHAR(250) NOT NULL,
contact VARCHAR(250) NOT NULL
);
DAO class should be like this.
***********************
public class EmployeeDao {
public int registerEmployee(Employee employee) throws ClassNotFoundException
{
String INSERT_USERS_SQL = "INSERT INTO employee "
+ "(first_name, last_name, username, password, address, contact) values "
+ "(?, ?, ?, ?, ?, ?);";
int result = 0;
Class.forName("com.mysql.jdbc.Driver");
try(
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost:3306/java", "root", "");
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL);
)
{
preparedStatement.setString(1, employee.getFirstName());
preparedStatement.setString(2, employee.getLastName());
preparedStatement.setString(3, employee.getUsername());
preparedStatement.setString(4, employee.getPassword());
preparedStatement.setString(5, employee.getAddress());
preparedStatement.setString(6, employee.getContact());
System.out.println(preparedStatement);
result = preparedStatement.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result;
}
}
The data is stored on the database. The table should be created like this. AUTO_INCREMENT should be used for the id.
ReplyDeleteCREATE TABLE employee
(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
username VARCHAR(250) NOT NULL,
PASSWORD VARCHAR(250) NOT NULL,
address VARCHAR(250) NOT NULL,
contact VARCHAR(250) NOT NULL
);
DAO class should be like this.
***********************
public class EmployeeDao {
public int registerEmployee(Employee employee) throws ClassNotFoundException
{
String INSERT_USERS_SQL = "INSERT INTO employee "
+ "(first_name, last_name, username, password, address, contact) values "
+ "(?, ?, ?, ?, ?, ?);";
int result = 0;
Class.forName("com.mysql.jdbc.Driver");
try(
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost:3306/java", "root", "");
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL);
)
{
preparedStatement.setString(1, employee.getFirstName());
preparedStatement.setString(2, employee.getLastName());
preparedStatement.setString(3, employee.getUsername());
preparedStatement.setString(4, employee.getPassword());
preparedStatement.setString(5, employee.getAddress());
preparedStatement.setString(6, employee.getContact());
System.out.println(preparedStatement);
result = preparedStatement.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result;
}
}
I am connected to PostgreSQL DB but data is not storing into database.
ReplyDeletesame here with mysql db
Deletedata is not storing on databases
ReplyDelete