Hi All,

Greetings of the day!

Today we will perform CRUD operations using JDBC, Servlet & JSP. I am assuming you have a basic idea of the servlet and its working if not visit my post.

What Is Servlet In Java? Servlet With Example + Servlet Lifecycle

So let's begin,

  • Create database test_db using cmd create database test_db;
  • Select test_db as the current database with the command use test_db;.
  • Create a table in MySQL which we will be used to perform CRUD. Below is a query for the same.

  • As we are using mysql we will add mysql dependency,also we will add jstl dependency in pom.xml.

  • Now create POJO Recipe.java with fields we have added in the table, also add getter, and setter. It will be used to pass data in the application.

  • Next, we will be adding RecipeDAO class where we will be adding methods to interact with the database.
  • After creating the class we will add the below method to add the recipe to the Recipe table. Here we have used PreparedStatement to execute the query.
  • Now add method to fetch all recipe from table.Here we have used ResultSet to iterate and create List of Recipe


  • Now add a method to fetch a single recipe using recipe id which will be used while we will be editing the recipe.
  • Now add a method to update & delete the recipe.


Now we have our repository layer ready, now let's create a controller class (Servlet for this example) to handle CRUD requests.

We will be using the same form for adding & editing recipes and we will handle either adding a new recipe or updating existing recipes in the controller using recipe id.

For displaying data on jsp we will be setting recipes in the request attribute after fetching from the database. Then we will forward a request to jsp & render data using JSTL.


We have called getAllBooks after delete, add & update so we can display recipes after each operation.

We are done with the back-end code. Let's add jsp code to create a recipe in add_recipe.jsp

add_recipe.jsp


Now create view_recipe.jsp to render all recipes, also here we will add links for edit & delete.


  
Inside index.jsp we will add links to add.jsp & view.jsp



We have completed the crud example.

I have attached the project structure for reference


If you have any questions let me know.

You can refer to the below post for more CRUD Examples







Other articles you may like to explore 




Thanks
Happy Learning!