CRUD stands for Create, Read, Update, and Delete, the basic operations used to manage data in any application. Using Java Servlets with JDBC, we can connect to a database and perform these operations through a web interface.
Key Components of CRUD
Create new users in the system.
Read and view user details from the database.
Update existing user information.
Delete users when needed.
Build a complete Servlet-based CRUD application with a frontend HTML form.
Let us see the backend code for it. First, let us see about the "Model" Java file. Here it is GeekUsers.java. It will contain some attributes similar to the columns of the MySQL table named "geekusers".
Explanation:
Define class attributes: Each attribute in GeekUsers corresponds to a column in the MySQL geekusers table.
Encapsulate fields: Attributes are private to ensure data integrity, and public getters and setters provide controlled access.
Object representation: Each GeekUsers object represents a single row in the database, allowing easy data manipulation in Java.
Data transfer: This class is used to transfer data between the frontend form, DAO, and servlets.
Step 4: Create DAO Class (GeekUsersDao.java)
The Data Access Object (DAO) provides methods for connecting to the database and performing CRUD operations.
Explanation:
Establish database connection: getConnection() sets up a connection to the MySQL database using JDBC.
CRUD methods: Includes save(), getAllGeekUsers(), getGeekUsersById(), update(), and delete() to perform database operations.
Use of PreparedStatement: Prevents SQL injection and safely executes SQL queries with parameters.
Data handling: DAO methods return objects, lists, or update status so servlets can handle results appropriately.
Step 5: Create Servlets
Let us see the servlet code now. From index.html, the input values are sent to "/SaveServlet". 'SaveServlet' is the servlet name that is looked up and 'POST' is the method that got called
5.1 Create Operation
Handles the form submission from index.html and saves a new GeekUser to the database.
Redirects to ViewServlet on success or shows an error message if saving fails.
SaveGeekUserServlet.java
Explanation:
Receive form data: Captures user input from index.html using request.getParameter().
Create a GeekUsers object: Sets the form values into a new GeekUsers instance.
Save to database: Calls GeekUsersDao.save() to insert the new record into MySQL.
Provide feedback: Shows a success message on the page or an error if saving fails.