Servlet – CRUD Operation with Example
CRUD means Create, Read, Update and Delete. These are the basic important operations carried out on the Database and in applications. We will build a simple User registration application using a Servlet, MYSQL, and JDBC for demonstration. In this example, we will be able to create users, read users, update users and delete users.
- MySQL(workbench) Database
- Apache Tomcat(I used the Tomcat 9 version).
First, we download Apache Tomcat from download Apache Tomcat, Extract into your working directory.
Then we create a new project, am naming it app user. Usually, there are two approaches to this, the first is to create your project from the Database and the other one is to create the application first then set up the Database. In this article, we will be starting our project from the Database. So, let us set up our database, in this example am making use of MYSQL, check the image below for the demonstration on how to set up the database.
After that we set up our project, for this example am using Intellij IDE,
- Create a new project by selecting File( it will show you various options)
- Select New, then project
- Click on Java Enterprise and choose web application as your project Template
Setting Up Application server
- Select the application and choose new
- Select Tomcat base directory(The one saved in your working directory)
This is what the project structure will look like:
The coding aspect. First, we create a model class called User, which is a simple POJO class;
Then we create a class that helps to perform CRUD operations on our database,
After, we create our Servlet classes, each servlet class for the Create user, Update user, Read user, and Delete User from the database. Here are the classes;
Add User Servlet:
This method does a post method, it collects users’ information and adds it to the database, in this example, we are making use of “username”, “password” and “userId” as the field to be saved into the database.
AddUser.java for adding users to the database.
Update User Servlet:
This method gets the user id and matches it to the one in the database, then does an update on it.
The Patch Method:
This method simply exchanges information on the database to the input parameters gotten from the web page and saves it into the database.
View user Servlet:
This method gets all users from the database and displays it in a simple table format.
The method below deletes the user from the database and sends the user view response, displaying the current users in the database.
The Java servlet renders the Java server page anytime a user calls.