Servlet Form Submit Tutorial with JDBC and MySQL
Author: Deep Singh | Category: Java, Servlet, JDBC, MySQL
Introduction
This tutorial demonstrates how to submit an HTML form to a Java Servlet and store the submitted data into a MySQL database using JDBC. The example uses a simple Student Registration form with fields like name, roll number, marks, gender, and course.
The project follows a clean layered architecture:
- Servlet — handles HTTP requests and form data
- DAO — handles database operations
- Model — represents the data object
Project Structure
StudentRegistration.java (Servlet)
The servlet handles both GET and POST requests, reads form parameters using request.getParameter(), populates the Student model, and delegates the insert operation to the DAO layer.
package com.deepsingh44.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.deepsingh44.dao.StudentDao;
import com.deepsingh44.model.Student;
@WebServlet("/register")
public class StudentRegistration extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Set MIME type
resp.setContentType("text/html");
// Get values from the student form
String name = req.getParameter("name");
String roll = req.getParameter("roll");
String marks = req.getParameter("marks");
String gender = req.getParameter("gender");
String course = req.getParameter("course");
// Set values in the model class
Student student = new Student();
student.setName(name);
student.setRoll(Integer.parseInt(roll));
student.setMarks(Float.parseFloat(marks));
student.setGender(gender);
student.setCourse(course);
// Pass student object to the database layer
// and get a callback to acknowledge the client
int i = StudentDao.getStudentDao().insert(student);
// Show result on the index.html page
if (i > 0) {
resp.getWriter().print("Successfully Student Added");
} else {
resp.getWriter().print("Student Added Failed");
}
// Include the index.html page in the response
req.getRequestDispatcher("index.html").include(req, resp);
}
}
Dao.java (Database Connection)
This utility class returns a shared JDBC connection for all DAO operations.
package com.deepsingh44.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Dao {
private static Connection connection;
// Return JDBC connection here for all DAOs
public static Connection getDatabaseConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb",
"root",
"root"
);
} catch (Exception e) {
System.out.println(e);
}
return connection;
}
}
StudentDao.java (DAO Layer)
This class implements the Singleton pattern to ensure only one instance exists, and provides an insert() method to store student records.
package com.deepsingh44.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.deepsingh44.model.Student;
public class StudentDao {
// Create a single instance here
private static StudentDao studentDao = new StudentDao();
// Prevent creating a new instance from outside the class
private StudentDao() {
}
// Share the instance using this method
public static StudentDao getStudentDao() {
return studentDao;
}
public int insert(Student student) {
int i = 0;
try (Connection con = Dao.getDatabaseConnection()) {
PreparedStatement ps = con.prepareStatement(
"insert into students values(?,?,?,?,?)"
);
ps.setString(1, student.getName());
ps.setInt(2, student.getRoll());
ps.setFloat(3, student.getMarks());
ps.setString(4, student.getGender());
ps.setString(5, student.getCourse());
i = ps.executeUpdate();
} catch (Exception e) {
System.out.println(e);
}
return i;
}
}
Student.java (Model Class)
A simple POJO that represents the student entity with getters and setters.
package com.deepsingh44.model;
public class Student {
private String name;
private int roll;
private float marks;
private String gender;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public float getMarks() {
return marks;
}
public void setMarks(float marks) {
this.marks = marks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
HTML Form
Create the HTML form as shown below. Make sure the action attribute points to the servlet URL (register) and the method is set to POST.
MySQL Database Setup
Run the following SQL commands in the MySQL command line to create the database and table:
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 248
Server version: 5.0.88-community-nt MySQL Community Edition (GPL)
mysql> create database studentdb;
Query OK, 1 row affected (0.02 sec)
mysql> use studentdb;
Database changed
mysql> create table students (
name varchar(35),
roll int primary key,
marks float,
gender varchar(15),
course varchar(20)
);
Query OK, 0 rows affected (0.09 sec)
mysql> desc students;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| name | varchar(35) | YES | | NULL | |
| roll | int(11) | NO | PRI | NULL | |
| marks | float | YES | | NULL | |
| gender | varchar(15) | YES | | NULL | |
| course | varchar(20) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
5 rows in set (0.03 sec)
mysql> select * from students;
Empty set (0.00 sec)
Output: After Form Submission
Once the form is submitted, the data is inserted into the students table. The table will look like this:
Conclusion
In this tutorial, we built a complete Servlet form submit example that stores user input into a MySQL database using JDBC. We followed a clean layered architecture with a servlet, DAO, and model class.
Key takeaways:
- HttpServlet handles both
GETandPOSTrequests viadoGet()anddoPost(). - request.getParameter() retrieves form field values by name.
- DAO pattern separates database logic from business logic.
- Singleton pattern ensures a single DAO instance across the application.
- PreparedStatement protects against SQL injection and simplifies parameter binding.
- RequestDispatcher.include() merges the servlet response with the original HTML page.
You can extend this example by adding form validation, session management, update/delete operations, or replacing the servlet with a modern framework like Spring MVC or Spring Boot. This foundational pattern is essential for building any Java web application that handles user input.
No comments:
Post a Comment