You are on page 1of 18

Programming Enthusiast

Blog about Java and OOP

A Simple CRUD Tutorial Using Java Servlet/JSP and MySQL

May 2, 2015May 17, 2015 Junald Bayog JAVA CRUD using jsp/servlet jdbc mysql, J2EE CRUD, jdbc CRUD,
servlet/jsp CRUD, simple java CRUD, studet CRUD, web application crud using java
In this tutorial, we will create a simple CRUD operations for a student using Servlet/JSP, JDBC and MySQL.

I assume you have already basic knowledge of Java.

For this tutorial, we need these following tools: (newer versions will do)

1. Eclipse IDE for Java EE Developers (h⸀ጅp://www.eclipse.org/downloads/), I use luna version


2. MySQL Community Server (h⸀ጅps://dev.mysql.com/downloads/mysql/)
3. Apache Tomcat 8.0 (h⸀ጅps://tomcat.apache.org/download‑80.cgi)
4. MySQL Connector Jar file, you can get this jar from your MySQL directory: C:\Program Files\MySQL\Connector.J 5.1.
5. servlet‑api.jar, you can get this jar from tomcat directory under lib folder. We need this jar to use the servlet library.
6. jstl.jar and standard.jar, you can get these jars in your tomcat directory \apache‑tomcat‑8.0.20\webapps\examples\WEB‑INF\lib.

Here is the project directory in case you miss something along the way:
After you have done installing the necessary tools, create a new dynamic web project in your eclipse IDE. Make sure you check “generate
After you have done installing the necessary tools, create a new dynamic web project in your eclipse IDE. Make sure you check “generate
web.xml” in the creation of the project.

Then copy the jars to the /WEB‑INF/lib (see the project directory above).

Create four packages under src folder:

com.junald.controller, contains the servlets


com.junald.dao, contains the classes or interfaces for the database logic operations.
com.junald.model, contains the Plain Old Java Object (POJO).
com.junald.util, contains the utility classes in our application. In this project, however, we only have one utility class and it is used for
connecting to the database.

We will create first our database table using this script:

1 CREATE TABLE `student` (


2 `studentId` int(5) NOT NULL AUTO_INCREMENT,
3 `firstName` varchar(25) DEFAULT NULL,
4 `lastName` varchar(25) DEFAULT NULL,
5 `course` varchar(15) DEFAULT NULL,
6 `year` int(2) DEFAULT NULL,
7 PRIMARY KEY (`studentId`));

Create a new class and name it “DBUtil” and put it under com.junald.util package. Then insert these following codes.

1 package com.junald.util;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.SQLException;
8 import java.util.Properties;
9
10 public class DBUtil {
11
12 private static Connection conn;
13
14 public static Connection getConnection() {
14 public static Connection getConnection() {
15 if( conn != null )
16 return conn;
17
18 InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream( "/db.properties" );
19 Properties properties = new Properties();
20 try {
21 properties.load( inputStream );
22 String driver = properties.getProperty( "driver" );
23 String url = properties.getProperty( "url" );
24 String user = properties.getProperty( "user" );
25 String password = properties.getProperty( "password" );
26 Class.forName( driver );
27 conn = DriverManager.getConnection( url, user, password );
28 } catch (IOException e) {
29 e.printStackTrace();
30 } catch (ClassNotFoundException e) {
31 e.printStackTrace();
32 } catch (SQLException e) {
33 e.printStackTrace();
34 }
35
36 return conn;
37 }
38
39 public static void closeConnection( Connection toBeClosed ) {
40 if( toBeClosed == null )
41 return;
42 try {
43 toBeClosed.close();
44 } catch (SQLException e) {
45 e.printStackTrace();
46 }
47 }
48 }

The class above is in charge of connecting and disconnecting to the database. Also it will retrieve database se⸀ጅings from a properties file.

Now create properties file, name it “db.properties” and put it under src folder. Then insert these codes.
Now create properties file, name it “db.properties” and put it under src folder. Then insert these codes.

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/UserDB (mysql://localhost:3306/UserDB)
3 user=mcjunald
4 password=hulaanmo

The se⸀ጅings above will vary depending what driver you use, database name, database username and password. Just make necessary
changes.

Create a new class and name it “Student” and put it under com.junald.model package. Then insert these following codes.

1 package com.junald.model;
2
3 public class Student {
4
5 private int studentId;
6 private String firstName;
7 private String lastName;
8 private String course;
9 private int year;
10
11 public int getStudentId() {
12 return studentId;
13 }
14 public void setStudentId(int studentId) {
15 this.studentId = studentId;
16 }
17 public String getFirstName() {
18 return firstName;
19 }
20 public void setFirstName(String firstName) {
21 this.firstName = firstName;
22 }
23 public String getLastName() {
24 return lastName;
25 }
26 public void setLastName(String lastName) {
27 this.lastName = lastName;
28 }
28 }
29 public String getCourse() {
30 return course;
31 }
32 public void setCourse(String course) {
33 this.course = course;
34 }
35 public int getYear() {
36 return year;
37 }
38 public void setYear(int year) {
39 this.year = year;
40 }
41 @Override
42 public String toString() {
43 return "Student [studentId=" + studentId + ", firstName=" + firstName
44 + ", lastName=" + lastName + ", course=" + course + ", year="
45 + year + "]";
46 }
47
48 }

The class above is just a POJO and each property of the class represents a field in our database table.

Now we will create the class and interface necessary for database logic operation.

Create a new interface, name it “StudentDAO” and put it under com.junald.dao package.

1 package com.junald.dao;
2
3 import java.util.List;
4
5 import com.junald.model.Student;
6
7 public interface StudentDAO {
8 public void addStudent( Student student );
9 public void deleteStudent( int studentId );
10 public void updateStudent( Student student );
11 public List<Student> getAllStudents();
12 public Student getStudentById( int studentId );
12 public Student getStudentById( int studentId );
13 }

By the way DAO means Data Access Object it is one of J2EE pa⸀ጅern. Please click this to learn more about DAO pa⸀ጅern.
(h⸀ጅp://www.oracle.com/technetwork/java/dataaccessobject‑138824.html)

Create a new class and name it “StudentDAOImplementation” and put it under com.junald.dao package.

1 package com.junald.dao;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 import com.junald.model.Student;
12 import com.junald.util.DBUtil;
13
14 public class StudentDAOImplementation implements StudentDAO {
15
16 private Connection conn;
17
18 public StudentDAOImplementation() {
19 conn = DBUtil.getConnection();
20 }
21 @Override
22 public void addStudent( Student student ) {
23 try {
24 String query = "insert into student (firstName, lastName, course, year) values (?,?,?,?)";
25 PreparedStatement preparedStatement = conn.prepareStatement( query );
26 preparedStatement.setString( 1, student.getFirstName() );
27 preparedStatement.setString( 2, student.getLastName() );
28 preparedStatement.setString( 3, student.getCourse() );
29 preparedStatement.setInt( 4, student.getYear() );
30 preparedStatement.executeUpdate();
31 preparedStatement.close();
32 } catch (SQLException e) {
32 } catch (SQLException e) {
33 e.printStackTrace();
34 }
35 }
36 @Override
37 public void deleteStudent( int studentId ) {
38 try {
39 String query = "delete from student where studentId=?";
40 PreparedStatement preparedStatement = conn.prepareStatement(query);
41 preparedStatement.setInt(1, studentId);
42 preparedStatement.executeUpdate();
43 preparedStatement.close();
44 } catch (SQLException e) {
45 e.printStackTrace();
46 }
47 }
48 @Override
49 public void updateStudent( Student student ) {
50 try {
51 String query = "update student set firstName=?, lastName=?, course=?, year=? where studentId=?"
52 PreparedStatement preparedStatement = conn.prepareStatement( query );
53 preparedStatement.setString( 1, student.getFirstName() );
54 preparedStatement.setString( 2, student.getLastName() );
55 preparedStatement.setString( 3, student.getCourse() );
56 preparedStatement.setInt( 4, student.getYear() );
57 preparedStatement.setInt(5, student.getStudentId());
58 preparedStatement.executeUpdate();
59 preparedStatement.close();
60 } catch (SQLException e) {
61 e.printStackTrace();
62 }
63 }
64 @Override
65 public List<Student> getAllStudents() {
66 List<Student> students = new ArrayList<Student>();
67 try {
68 Statement statement = conn.createStatement();
69 ResultSet resultSet = statement.executeQuery( "select * from student" );
70 while( resultSet.next() ) {
71 Student student = new Student();
71 Student student = new Student();
72 student.setStudentId( resultSet.getInt( "studentId" ) );
73 student.setFirstName( resultSet.getString( "firstName" ) );
74 student.setLastName( resultSet.getString( "lastName" ) );
75 student.setCourse( resultSet.getString( "course" ) );
76 student.setYear( resultSet.getInt( "year" ) );
77 students.add(student);
78 }
79 resultSet.close();
80 statement.close();
81 } catch (SQLException e) {
82 e.printStackTrace();
83 }
84 return students;
85 }
86 @Override
87 public Student getStudentById(int studentId) {
88 Student student = new Student();
89 try {
90 String query = "select * from student where studentId=?";
91 PreparedStatement preparedStatement = conn.prepareStatement( query );
92 preparedStatement.setInt(1, studentId);
93 ResultSet resultSet = preparedStatement.executeQuery();
94 while( resultSet.next() ) {
95 student.setStudentId( resultSet.getInt( "studentId" ) );
96 student.setFirstName( resultSet.getString( "firstName" ) );
97 student.setLastName( resultSet.getString( "LastName" ) );
98 student.setCourse( resultSet.getString( "course" ) );
99 student.setYear( resultSet.getInt( "year" ) );
100 }
101 resultSet.close();
102 preparedStatement.close();
103 } catch (SQLException e) {
104 e.printStackTrace();
105 }
106 return student;
107 }
108
109 }
The class above is necessary for CRUD operations in the database.

Now we will create the main controller or the servlet of the application.

Create a new servlet and name it “StudentController” and put it under com.junald.controller package. Here is the code.

1 package com.junald.controller;
2
3 import java.io.IOException;
4
5 import javax.servlet.RequestDispatcher;
6 import javax.servlet.ServletException;
7 import javax.servlet.annotation.WebServlet;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import com.junald.dao.StudentDAO;
13 import com.junald.dao.StudentDAOImplementation;
14 import com.junald.model.Student;
15
16 @WebServlet("/StudentController")
17 public class StudentController extends HttpServlet {
18
19 private StudentDAO dao;
20 private static final long serialVersionUID = 1L;
21 public static final String lIST_STUDENT = "/listStudent.jsp";
22 public static final String INSERT_OR_EDIT = "/student.jsp";
23
24 public StudentController() {
25 dao = new StudentDAOImplementation();
26 }
27
28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, I
29 String forward = "";
30 String action = request.getParameter( "action" );
31
32 if( action.equalsIgnoreCase( "delete" ) ) {
33 forward = lIST_STUDENT;
32 if( action.equalsIgnoreCase( "delete" ) ) {
33 forward = lIST_STUDENT;
34 int studentId = Integer.parseInt( request.getParameter("studentId") );
35 dao.deleteStudent(studentId);
36 request.setAttribute("students", dao.getAllStudents() );
37 }
38 else if( action.equalsIgnoreCase( "edit" ) ) {
39 forward = INSERT_OR_EDIT;
40 int studentId = Integer.parseInt( request.getParameter("studentId") );
41 Student student = dao.getStudentById(studentId);
42 request.setAttribute("student", student);
43 }
44 else if( action.equalsIgnoreCase( "insert" ) ) {
45 forward = INSERT_OR_EDIT;
46 }
47 else {
48 forward = lIST_STUDENT;
49 request.setAttribute("students", dao.getAllStudents() );
50 }
51 RequestDispatcher view = request.getRequestDispatcher( forward );
52 view.forward(request, response);
53 }
54
55 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
56 Student student = new Student();
57 student.setFirstName( request.getParameter( "firstName" ) );
58 student.setLastName( request.getParameter( "lastName" ) );
59 student.setCourse( request.getParameter( "course" ) );
60 student.setYear( Integer.parseInt( request.getParameter( "year" ) ) );
61 String studentId = request.getParameter("studentId");
62
63 if( studentId == null || studentId.isEmpty() )
64 dao.addStudent(student);
65 else {
66 student.setStudentId( Integer.parseInt(studentId) );
67 dao.updateStudent(student);
68 }
69 RequestDispatcher view = request.getRequestDispatcher( lIST_STUDENT );
70 request.setAttribute("students", dao.getAllStudents());
71 view.forward(request, response);
72 }
72 }
73 }

We need a form for inserting students data. So create a new JSP and name it “student.jsp“. Then insert the following code.

1 <%@ page language="java" contentType="text/html; charset=ISO‐8859‐1"


2 pageEncoding="ISO‐8859‐1"%>
3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core (http://java.sun.com/jsp/jstl/core)" prefix="c"%>
4 <!DOCTYPE HTML>
5 <html>
6 <head>
7 <meta http‐equiv="Content‐Type" content="text/html; charset=ISO‐8859‐1">
8
9 <title>Add New Student</title>
10 </head>
11 <body>
12 <form action="StudentController.do" method="post">
13 <fieldset>
14 <div>
15 <label for="studentId">Student ID</label> <input type="text"
16 name="studentId" value="<c:out value="${student.studentId}" />"
17 readonly="readonly" placeholder="Student ID" />
18 </div>
19 <div>
20 <label for="firstName">First Name</label> <input type="text"
21 name="firstName" value="<c:out value="${student.firstName}" />"
22 placeholder="First Name" />
23 </div>
24 <div>
25 <label for="lastName">Last Name</label> <input type="text"
26 name="lastName" value="<c:out value="${student.lastName}" />"
27 placeholder="Last Name" />
28 </div>
29 <div>
30 <label for="course">Course</label> <input type="text" name="course"
31 value="<c:out value="${student.course}" />" placeholder="Course" />
32 </div>
33 <div>
34 <label for="year">Year</label> <input type="text" name="year"
34 <label for="year">Year</label> <input type="text" name="year"
35 value="<c:out value="${student.year}" />" placeholder="Year" />
36 </div>
37 <div>
38 <input type="submit" value="Submit" />
39 </div>
40 </fieldset>
41 </form>
42 </body>
43 </html>

And for displaying the students data, we need to create a new JSP and name it “listStudent.jsp“. Then insert the following code.

1 <%@ page language="java" contentType="text/html; charset=ISO‐8859‐1"


2 pageEncoding="ISO‐8859‐1"%>
3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core (http://java.sun.com/jsp/jstl/core)" prefix="c"%>
4 <!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd (http://
5 <html>
6 <head>
7 <meta http‐equiv="Content‐Type" content="text/html; charset=ISO‐8859‐1">
8 <title>Show All Students</title>
9 </head>
10 <body>
11 <table>
12 <thead>
13 <tr>
14 <th>Student ID</th>
15 <th>First Name</th>
16 <th>Last Name</th>
17 <th>Course</th>
18 <th>Year</th>
19 <th colspan="2">Action</th>
20 </tr>
21 </thead>
22 <tbody>
23 <c:forEach items="${students}" var="student">
24 <tr>
25 <td><c:out value="${student.studentId}" /></td>
26 <td><c:out value="${student.firstName}" /></td>
27 <td><c:out value="${student.lastName}" /></td>
27 <td><c:out value="${student.lastName}" /></td>
28 <td><c:out value="${student.course}" /></td>
29 <td><c:out value="${student.year}" /></td>
30 <td><a
31 href="StudentController.do?action=edit&studentId=<c:out value="${student.studentId }
32 <td><a
33 href="StudentController.do?action=delete&studentId=<c:out value="${student.studentId
34 </tr>
35 </c:forEach>
36 </tbody>
37 </table>
38 <p>
39 <a href="StudentController.do?action=insert">Add Student</a>
40 </p>
41 </body>
42 </html>

For the default page of the application, create a new JSP file and name it index.jsp. Then insert the following code.

1 <%@ page language="java" contentType="text/html; charset=ISO‐8859‐1"


2 pageEncoding="ISO‐8859‐1"%>
3 <!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd (http://
4 <html>
5 <head>
6 <meta http‐equiv="Content‐Type" content="text/html; charset=ISO‐8859‐1">
7 <title>Welcome</title>
8 </head>
9 <body>
10 <jsp:forward page="/StudentController?action=listStudent"></jsp:forward>
11 </body>
12 </html>

And finally, the code for our deployment descriptor define in the web.xml. Make sure it is the same as the code below.

1 <?xml version="1.0" encoding="UTF‐8"?>


2 <web‐app xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance (http://www.w3.org/2001/XMLSchema‐instance)
3 <display‐name>CRUD Project</display‐name>
4 <welcome‐file‐list>
4 <welcome‐file‐list>
5 <welcome‐file>index.jsp</welcome‐file>
6 </welcome‐file‐list>
7 <servlet>
8 <servlet‐name>StudentController</servlet‐name>
9 <servlet‐class>com.junald.controller.StudentController</servlet‐class>
10 </servlet>
11 <servlet‐mapping>
12 <servlet‐name>StudentController</servlet‐name>
13 <url‐pattern>/StudentController.do</url‐pattern>
14 </servlet‐mapping>
15 </web‐app>

So we are done. Run it using your tomcat server!

If you want to learn more about servlets and JSP’s, I would recommend a book: Head First Sevlet/JSP
(h⸀ጅp://www.headfirstlabs.com/books/hfsvlt/).

You can download the all source code from my Github account. (h⸀ጅps://github.com/junaldbayog/ServletJspCRUDProject)

If you liked this tutorial, please subcribe or follow to my blog and like my facebook page.
If you liked this tutorial, please subcribe or follow to my blog and like my facebook page.

8 thoughts on “A Simple CRUD Tutorial Using Java Servlet/JSP


and MySQL”

1. chaudharisuresh997 says:
May 2, 2015 at 5:52 pm
Reblogged this on Instantsketchʹs Blog (h⸀ጅps://instantsketch.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑
and‑mysql/) and commented:
Very basic tutorial

Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
replytocom=1#respond)
chaudharisuresh997 says:
May 3, 2015 at 5:19 am
Plz visit h⸀ጅp://www.eye2you.WordPress.com (h⸀ጅp://www.eye2you.WordPress.com)

Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
replytocom=2#respond)
2. Strong World D Hack says:
January 6, 2016 at 9:23 pm
Hello, I wish for to subscribe for this webpage to obtain ho⸀ጅest updates, so where can i do it please assist.

Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
replytocom=39#respond)
3. Bwalya Chisukulu Jr. says:
February 19, 2016 at 12:20 pm
Suppose I want to perform a calculation in the servlet with data that’s being captured from the form and have it submi⸀ጅed as a form
entry to database, how would I go about it based on this tutorial?

Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
replytocom=47#respond)
Junald Bayog says:
February 19, 2016 at 12:32 pm
You can get those data by using the request object of H⸀ጅpServletRequest in the doGet or doPost. For example, number1 =
request.getParameter(“num1”); num1 is the name of the text field in your html. So, get all data that are needed for calculation.

Reply (h⸀ጅps://programmingenthusiast.wordpress.com/2015/05/02/a‑simple‑crud‑tutorial‑using‑java‑servletjsp‑and‑mysql/?
replytocom=48#respond)
Bwalya Chisukulu Jr. says:
February 19, 2016 at 1:24 pm
Should I assign number1 to type String? String number1 = request.getParamater(“num1”); ?

Bwalya Chisukulu Jr. says:


February 19, 2016 at 1:48 pm
And then convert it to a type int or BigDecimal? When I convert to type BigDecimal, I get a null error exception.
BigDecimal number = new BigDecimal(number1);

Bwalya Chisukulu Jr. says:


February 20, 2016 at 2:52 pm
Solved it. Naming typo in the html. Thanks a lot.

Create a free website or blog at WordPress.com. (h⸀ጅps://wordpress.com/?ref=footer_website) The Big Brother Theme
(h⸀ጅps://wordpress.com/themes/big‑brother/).

You might also like