How to insert data in MySql Using JSP Servlet & JDBC

Here we will insert data in MySQL using JSP Servlet and JDBC.

Here We will fetch Data from the JSP page and pass it to Servlet then DAO which contains JDBC code to store data in the MySQL database.

How To Get Data From Database To Servlet Jdbc JSP

Technology used

  1. apache-tomcat-10.1.1
  2. JavaSE-17
  3. eclipse IDE for Enterprise Java and Web Developers

Steps for Data insertion using Jsp Servlet

  1. Create MySql Table
  2. Create a Dynamic Web Project
  3. Create package structure
  4. Create Java files
  5. Create JSP Pages

1 Create MySql Table

Creating Java Dynamic Web Project

Open Eclipse IDE and follow the below steps

  1. Click on File->New-> Dynamic Web Project.
  2. Give project Name
  3. Select Target runtime (here apache-tomcat-10.1.1)
  4. then next again next then finish.

create package structure for storing servlet, model, and DAO.

Project Explorer

insert data in MySql Using JSP Servlet & JDBC Project Explorer
Fig: Project Explorer

External Jar

The following External jars are included in the apache tomcat lib folder

  1. mysql-connector-java-8.0.30

JSP Page to insert student record -insert.jsp

Servlet class to get Student Data from JSP- InsertStudentServlet.java

This servlet accepts data from JSP using a request object and getParameter() and store all data in student object.

Student object is passed to StudentDAO insert() to save data in MySQL database.

If data is inserted then the request response is forwarded to home.jsp.

In case of error, it is again sent back to insert.jsp.

DAO class for JDBC connection and record insertion

ConnectionFactory.java

This class returns the connection object.

StudentDAO.java

This class contains the logic of data insertion to the database. JDBC Prepared statement is used to save data in Database.

Student Model class Student.java

JSp Page on successful insertion – Home.jsp

Result

insert.jsp

This page contains all fields of students.

This will pass to InsertStudentServlet.java. that passes the student model to StudentDAO that saves data to the database.

JSP page to store student record in MySQL database

home.jsp

On successful insertion, it will be redirected to the home page and shows the following message.

Home. jsp page  after JDBC Insert

Here we discussed How to insert data in MySql Using JSP Servlet & JDBC