Servlet Form Submit Tutorial with JDBC

Project Structure:

StudentRegistration.java


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 value from 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 Value in your 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 database layer to store and get a callback
	//  from there to give acknowledge to client or student.
	int i = StudentDao.getStudentDao().insert(student);
		
    // show result in index.html page
	if (i > 0) {
		resp.getWriter().print("Successfully Student Added");
	} else {
		resp.getWriter().print("Student Added Failed");
	}
		
     // this method is used to call another page and include method is 
	// used to add current page response to requested page.
	req.getRequestDispatcher("index.html").include(req, resp);
}

}
 

Dao.java


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.
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


package com.deepsingh44.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import com.deepsingh44.model.Student;

public class StudentDao {
	// create an instance here
	private static StudentDao studentDao = new StudentDao();

	// prevent to create a new instance from outside of class.
	private StudentDao() {
	}

	// share instance using this method to call you methods
	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


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

}
  

Create Form like below:

Mysql Panel:

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)

After Submit Table is like below:

No comments: