In this example, we will write JDBC code separate from the JSP page because it is good practice to separate Java code from the JSP page. JSP page we will be using only for presentation.
You can download the source code of this article from my GitHub repository. The link is given at the end of this article.
You can download the source code of this article from my GitHub repository. The link is given at the end of this article.
Tools and technologies used
- JSP - 2.2 +
- IDE - STS/Eclipse Neon.3
- JDK - 1.8 or later
- Apache Tomcat - 8.5
- JSTL - 1.2.1
- MySQL - mysql-connector-java-8.0.13.jar
Development Steps
- Create Eclipse Dynamic Web Project
- Add Dependencies
- Project Structure
- MySQL Database Setup
- Create a JavaBean - Employee.java
- Create an EmployeeDao.java
- Create a employeeregister.jsp
- Create a employeedetail.jsp
- 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 "jsp-jdbc-mysql-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 the below jar files to the lib folder.
- jsp-api.2.3.1.jar
- servlet-api.2.3.jar
- mysql-connector-java-8.0.13.jar
4. MySQL Database Setup
Let's create a database named "mysql_database" in MySQL. Now, create an employee table using the DDL script:
CREATE TABLE `employee` (
`id` int(3) NOT NULL,
`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;
SELECT * FROM mysql_database.employee;
5. Create a JavaBean - Employee.java
Let's create an Employee JavaBean class, which we will use in JSP action tags.
package net.javaguides.jsp.jdbc.bean;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1 L;
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;
}
}
6. Create an EmployeeDao.java
We will separate the JDBC accessing code from JSP. So let's create an EmployeeDao class under net.javaguides.jsp.jdbc.database package and add the following code to it:
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" +
" (id, 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/mysql_database?useSSL=false", "root", "root");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, employee.getFirstName());
preparedStatement.setString(3, employee.getLastName());
preparedStatement.setString(4, employee.getUsername());
preparedStatement.setString(5, employee.getPassword());
preparedStatement.setString(6, employee.getAddress());
preparedStatement.setString(7, 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();
}
}
}
}
}
You can learn complete JDBC at JDBC Tutorial
7. Create a employeeregister.jsp
Let's design an employee registration HTML form with the following fields:
- firstName
- lastName
- username
- password
- address
- contact
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Employee Register Form</h1>
<form action="employeedetails.jsp" method="post">
<table style="with: 50%">
<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>
</body>
</html>
8. Create a employeedetail.jsp
After an employee successfully registered, next, let's create a JSP page to show the successful message on the screen:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="net.javaguides.jsp.jdbc.database.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="employee"
class="net.javaguides.jsp.jdbc.bean.Employee" />
<jsp:setProperty property="*" name="employee" />
<%
EmployeeDao employeeDao = new EmployeeDao();
int status = employeeDao.registerEmployee(employee);
if (status > 0) {
out.print("You are successfully registered");
}
%>
</body>
</html>
Note that in the above page, we have used JSP action tags. Read more about action tags here.
9. Demo
It's time to see a demo of the above development. Deploy this web application in the Tomcat server.
Employee Registration
Once you deploy this application successfully, then hit this link into a browser - http://localhost:8080/jsp-jdbc-mysql-example/employeeregister.jsp
Registration Success Page
GitHub Repository
In the next article, we will look into case studies of using JSP and JDBC at JSP Registration Form + JDBC + MySQL Example
Comments
Post a Comment
Leave Comment