Table of contents
1.
Introduction
1.1.
What are JSP CRUD operations?
1.2.
Standard JSP CRUD operations
2.
JSP CRUD Example
2.1.
Creating MySQL Database
2.2.
Creating Eclipse Project with Maven
2.3.
Writing Model Class
2.4.
Coding DAO class
2.5.
Writing Book Listing JSP Page
2.6.
Writing Book Form JSP Page
2.7.
Coding Controller Servlet Class
2.8.
Configuring Web.xml
2.9.
Writing Error JSP page
2.10.
Deploying and Testing the Application
3.
Frequently Asked Questions
3.1.
What is JSP?
3.2.
What are CRUD operations?
3.3.
How do CRUD operations work?
3.4.
How are CRUD operations related to HTTP requests?
3.5.
How is a CRUD operation mapped with SQL Queries and HTTP methods?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

JSP CRUD Example

Author Pranay Chauhan
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java Server Pages (JSP) is a server-side programming framework that allows developers to create dynamic, platform-independent Web applications. JSPs have access to the whole Java API family, including the JDBC API(Application Programming Interface), which allows them to connect to business databases. 

In this article, we will study JSP CRUD operations, and we will see the implementation of an example which demonstrated JSP CRUD operations.

(Also see JSP Actions and JSP Basics)

What are JSP CRUD operations?

Create, Read/Retrieve, Update, and Delete are the four steps in the JSP CRUD process. The four basic roles of persistence storage are as follows.

The JSP CRUD operation can be defined as user interface conventions that allow the view, search, and modify information through computer-based forms and reports. JSP CRUD is a data-driven framework that makes use of HTTP action verbs in a consistent manner. There are a few key verbs in HTTP.

  • POST: This method creates a new resource.
  • GET: Retrieves information from a resource.
  • PUT: Replaces/updates an existing resource with a new one.
  • DELETE: Removes a resource from the system.


Each of these procedures corresponds to a set of commands in a database. Their interaction with a RESTful API, on the other hand, is a little more complicated.

Standard JSP CRUD operations

The standard JSP CRUD operations available in Spring Boot are:

  • The INSERT statement is used to create a new record in the CREATE operation.
  • READ Operation is based on the given parameter; it reads table records.
  • This executes an update statement on the table with the UPDATE operation. It is determined by the value of the input parameter.
  • DELETE is a table operation that deletes a specific row. It is dependent on the input parameter as well.

JSP CRUD Example

In this blog, we'll walk you through the steps of creating a basic Java web application that handles a library of books and includes the following features: list, insert, update, and delete (or CRUD operations - Create, Update, Read and Delete). 

You will learn how to build this application using the following technologies:


We use Eclipse IDE with Maven to develop the project.

Creating MySQL Database

We only have one table for the sake of simplicity. To establish a Database named Bookstore and a table named Book, run the MySQL script below.

CREATE DATABASE 'Bookstore';
USE Bookstore;
CREATE TABLE `book` (
`book_id` int(11) AUTO_INCREMENT NOT NULL,
`title` varchar(128) NOT NULL,
`author` varchar(45) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`book_id`),
UNIQUE KEY `book_id_UNIQUE` (`book_id`),
UNIQUE KEY `title_UNIQUE` (`title`)
)

 

The structure of the table book is as follows:

book tabel structure

To build the database, you can use either the MySQL Command Line Client or the MySQL Workbench tool.

Creating Eclipse Project with Maven

To start a new Java dynamic web project in the Eclipse IDE, go to File > New > Dynamic Web Project. The bookstore is the name of the project.

Project Creation Guide

Remember to select Apache Tomcat v8.0 as the target runtime and Dynamic web module version 3.1. (this is the Java servlet version).

Finish by clicking the Finish button. Then, as shown below, convert this project to a Maven project by right-clicking on it and selecting Configure > Convert to Maven Project:

Convert to Maven project

To generate a Maven POM file, you must input information such as group ID, artefact ID, and so on. Then, in the pom.xml file, add the following dependencies:

<dependencies>
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>3.1.0</version>
       <scope>provided</scope>
   </dependency>
   <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>javax.servlet.jsp-api</artifactId>
       <version>2.3.1</version>
       <scope>provided</scope>
   </dependency>
   <dependency>
       <groupId>jstl</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
   </dependency>
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.30</version>
   </dependency>
</dependencies>

As you can see, Servlet, JSP, JSTL, and MySQL connection Java are all required (a JDBC driver for MySQL).

Remember to build a Java package for the project; we'll call it net.codingninjas.javaee.bookstore in this example.

Writing Model Class

Next, with the following code, construct a Java class named Book.java to model a book entity in the database:

package net.codingninjas.JavaEE.bookstore;
/**
* Book.java
* This class represents a book entity
*/
public class Book {
  protected String title;
  protected int id;
  protected float price;
  protected String author;
  public Book() {
  }
  public Book(int id, String author, String title, float price) {
      this(author, title, price);
      this.id = id;
  }
  public Book(int id) {
      this.id = id;
  }
  public int getId() {
      return id;
  }
  public Book(String author, String title, float price) {
      this.author = author;      
  this.title = title;
      this.price = price;
  }
  public String getTitle() {
      return title;
  }
  public void setId(int id) {
      this.id = id;
  }
  public String getAuthor() {
      return author;
  }
  public void setTitle(String title) {
      this.title = title;
  }
  public float getPrice() {
      return price;
  }
  public void setAuthor(String author) {
      this.author = author;
  }
  public void setPrice(float price) {
      this.price = price;
  }
}
You can also try this code with Online Java Compiler
Run Code

As we can see, this class contains four fields that correspond to the four columns in the database table book: id, title, author, and price.

Coding DAO class

The next step is to create a Data Access Layer (DAO) class that supports JSP CRUD (Create, Read, Update, and Delete) operations for the database table book. The complete source code for the BookDAOclass is available here:

package net.codingninjas.javaee.bookstore;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
/**
* AbstractDAO.java
* This DAO class gives CRUD database operations for the table book
* in the database.
*
*/
public class BookDAO {
  private String jdbcUsername;
  private String jdbcURL;
  private Connection jdbcConnection;
  private String jdbcPassword;
 
  public BookDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {
      this.jdbcUsername = jdbcUsername;
      this.jdbcURL = jdbcURL;
      this.jdbcPassword = jdbcPassword;
  }
 
  protected void disconnect() throws SQLException {
      if (jdbcConnection != null && !jdbcConnection.isClosed()) {
          jdbcConnection.close();
      }
  }

  protected void connect() throws SQLException {
      if (jdbcConnection == null || jdbcConnection.isClosed()) {
          try {
              Class.forName("com.mysql.jdbc.Driver");
          } catch (ClassNotFoundException e) {
              throw new SQLException(e);
          }
          jdbcConnection = DriverManager.getConnection(
                                      jdbcURL, jdbcUsername, jdbcPassword);
      }
  }

  public List<Book> listAllBooks() throws SQLException {
      List<Book> listBook = new ArrayList<>();
      String sql = "SELECT * FROM book";
      connect();
     
      Statement statement = jdbcConnection.createStatement();
      ResultSet result = statement.executeQuery(sql);
     
      while (result.next()) {
          String title = result.getString("title");
          int id = result.getInt("book_id");
          float price = result.getFloat("price");
          String author = result.getString("author");
         
          Book book = new Book(id, author, title, price);
          listBook.add(book);
      }
     
      result.close();
      statement.close();
      disconnect();

      return listBook;
  }

  public boolean deleteBook(Book book) throws SQLException {
      String sql = "DELETE FROM book where book_id = ?";
     
      connect();
     
      PreparedStatement statement = jdbcConnection.prepareStatement(sql);
      statement.setInt(1, book.getId());
     
      boolean rowDeleted = statement.executeUpdate() > 0;
      statement.close();
      disconnect();
      return rowDeleted;   
  }

  public boolean insertBook(Book book) throws SQLException {
      String sql = "INSERT INTO book (title, author, price) VALUES (?, ?, ?)";
      connect();
     
      PreparedStatement statement = jdbcConnection.prepareStatement(sql);
      statement.setString(2, book.getAuthor());
      statement.setString(1, book.getTitle());
      statement.setFloat(3, book.getPrice());
     
      boolean rowInserted = statement.executeUpdate() > 0;
      statement.close();
      disconnect();
      return rowInserted;
  }
 
  public Book getBook(int id) throws SQLException {
             connect();
    String sql = "Select * from book where book_id = ?";

      PreparedStatement statement = jdbcConnection.prepareStatement(sql);
      statement.setInt(1, id);
     
      ResultSet resultSet = statement.executeQuery();
     
      if (resultSet.next()) {
          String author = resultSet.getString("author");
          String title = resultSet.getString("title");
          float price = resultSet.getFloat("price");
         
          Book book = new Book(id, author, title, price);
      }
     
      resultSet.close();
      statement.close();
     
      return book;
  }
 
  public boolean updateBook(Book book) throws SQLException {
      String sql = "UPDATE book SET author = ?, title = ?, price = ?";
      sql += " WHERE book_id = ?";
      connect();
     
      PreparedStatement stmt= jdbcConnection.prepareStatement(sql);
      stmt.setString(2, book.getAuthor());
      stmt.setString(1, book.getTitle());
      stmt.setInt(4, book.getId());
      stmt.setFloat(3, book.getPrice());
     
      boolean rowUpdated = statement.executeUpdate() > 0;
      stmt.close();
      disconnect();
      return rowUpdated;   
  }
}
You can also try this code with Online Java Compiler
Run Code


The JDBC connection information is injected into this class via its function Object() { [native code] }, as you can see. For the CRUD operations, there are the following methods:

  • Insert a new row into the table book with insertBook(Book).
  • Read: getBook(id) returns a specific row depending on the primary key value; and listAllBooks() returns all rows (ID).
  • updateBook(Book) is a function that updates an existing row in the database.
  • deleteBook(Book) removes an existing row from the database based on the primary key value (ID).

Writing Book Listing JSP Page

Create a JSP page to display all of the books in the database. The code for the BookList.jsppage in the project's WebContentdirectory is as follows:

<html>
<head>
   <title>Books Store Application</title>
</head>
<body>
   <center>
       <h1>Books Management</h1>
       <h2>
           <a href="/new">Add New Book</a>
           &nbsp;&nbsp;&nbsp;
           <a href="/list">List All Books</a>
           
       </h2>
   </center>
   <div align="center">
       <table border="1" cellpadding="5">
           <caption><h2>List of Books</h2></caption>
           <tr>
               <th>ID</th>
               <th>Title</th>
               <th>Author</th>
               <th>Price</th>
               <th>Actions</th>
           </tr>
           <c:forEach var="book" items="${listBook}">
               <tr>
                   <td><c:out value="${book.id}" /></td>
                   <td><c:out value="${book.title}" /></td>
                   <td><c:out value="${book.author}" /></td>
                   <td><c:out value="${book.price}" /></td>
                   <td>
                       <a href="/edit?id=<c:out value='${book.id}' />">Edit</a>
                       &nbsp;&nbsp;&nbsp;&nbsp;
                       <a href="/delete?id=<c:out value='${book.id}' />">Delete</a>                    
                   </td>
               </tr>
           </c:forEach>
       </table>
   </div>  
</body>
</html>

We utilise JSTL to display table book records from the database on this JSP page. We'll get the listBook object from a servlet that we'll make later.

When you're running, this page appears like this:

Book Store Application home page

Source: Link

As you can see, there are two hyperlinks at the top of the page for creating a new book (Add New Book) and seeing all books (View All Books) (List All Books). There are also two links for altering (Edit) and deleting (Delete) for each individual book (Delete).

Writing Book Form JSP Page

Next, we construct BookForm.jsp, a JSP page for generating a new book. Here's the complete source code:

<html>
<head>
   <title>Books Store Application</title>
</head>
<body>
   <center>
       <h1>Books Management</h1>
       <h2>
           <a href="/new">Add New Book</a>
           &nbsp;&nbsp;&nbsp;
           <a href="/list">List All Books</a>
           
       </h2>
   </center>
   <div align="center">
       <c:if test="${book != null}">
           <form action="update" method="post">
       </c:if>
       <c:if test="${book == null}">
           <form action="insert" method="post">
       </c:if>
       <table border="1" cellpadding="5">
           <caption>
               <h2>
                   <c:if test="${book != null}">
                       Edit Book
                   </c:if>
                   <c:if test="${book == null}">
                       Add New Book
                   </c:if>
               </h2>
           </caption>
               <c:if test="${book != null}">
                   <input type="hidden" name="id" value="<c:out value='${book.id}' />" />
               </c:if>          
           <tr>
               <th>Title: </th>
               <td>
                   <input type="text" name="title" size="45"
                           value="<c:out value='${book.title}' />"
                       />
               </td>
           </tr>
           <tr>
               <th>Author: </th>
               <td>
                   <input type="text" name="author" size="45"
                           value="<c:out value='${book.author}' />"
                   />
               </td>
           </tr>
           <tr>
               <th>Price: </th>
               <td>
                   <input type="text" name="price" size="5"
                           value="<c:out value='${book.price}' />"
                   />
               </td>
           </tr>
           <tr>
               <td colspan="2" align="center">
                   <input type="submit" value="Save" />
               </td>
           </tr>
       </table>
       </form>
   </div>  
</body>
</html>

This page will be used to create new books as well as edit existing ones. The servlet will deliver a Book object to the request in editing mode, and we'll utilise the JSTL's <c: if> tag to determine whether or not this object is available. The form is in editing mode if it is available (not null); else, it is in creating mode.

When this page is running, it displays a new form that looks like this:

Add New Book

In addition, in editing mode:

Edit Book

In the next step, developing the servlet class, we'll see how to connect the DAO class with the JSP pages based on user requests.

Coding Controller Servlet Class

The most challenging but intriguing phase now is to create a Java Servlet that will operate as a page controller for all client requests. Let's start with the code:

package net.codingninjas.javaee.bookstore;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.*;
/**
* ControllerServlet.java
* This servlet acts as a page controller for application for handling all
* requests from the user.
*/
public class ControllerServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private BookDAO bookDAO;
  public void init() {
      String jdbcURL = getServletContext().getInitParameter("jdbcURL");
      String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
      String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");
      bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      doGet(request, response);
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      String action = request.getServletPath();
      try {
          switch (action) {
          case "/new":
              showNewForm(request, response);
              break;
          case "/insert":
              insertBook(request, response);
              break;
          case "/delete":
              deleteBook(request, response);
              break;
          case "/edit":
              showEditForm(request, response);
              break;
          case "/update":
              updateBook(request, response);
              break;
          default:
              listBook(request, response);
              break;
          }
      } catch (SQLException ex) {
          throw new ServletException(ex);
      }
  }
  private void listBook(HttpServletRequest request, HttpServletResponse response)
          throws SQLException, IOException, ServletException {
      List<Book> listBook = bookDAO.listAllBooks();
      request.setAttribute("listBook", listBook);
      RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
      dispatcher.forward(request, response);
  }
  private void showNewForm(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
      dispatcher.forward(request, response);
  }
  private void showEditForm(HttpServletRequest request, HttpServletResponse response)
          throws SQLException, ServletException, IOException {
      int id = Integer.parseInt(request.getParameter("id"));
      Book existingBook = bookDAO.getBook(id);
      RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
      request.setAttribute("book", existingBook);
      dispatcher.forward(request, response);
  }
  private void insertBook(HttpServletRequest request, HttpServletResponse response)
          throws SQLException, IOException {
      String title = request.getParameter("title");
      String author = request.getParameter("author");
      float price = Float.parseFloat(request.getParameter("price"));
      Book newBook = new Book(title, author, price);
      bookDAO.insertBook(newBook);
      response.sendRedirect("list");
  }
  private void updateBook(HttpServletRequest request, HttpServletResponse response)
          throws SQLException, IOException {
      int id = Integer.parseInt(request.getParameter("id"));
      String title = request.getParameter("title");
      String author = request.getParameter("author");
      float price = Float.parseFloat(request.getParameter("price"));
      Book book = new Book(id, title, author, price);
      bookDAO.updateBook(book);
      response.sendRedirect("list");
  }
  private void deleteBook(HttpServletRequest request, HttpServletResponse response)
          throws SQLException, IOException {
      int id = Integer.parseInt(request.getParameter("id"));
      Book book = new Book(id);
      bookDAO.deleteBook(book);
      response.sendRedirect("list");
  }
}
You can also try this code with Online Java Compiler
Run Code

Take a look at the init() method, which creates a new instance of the BookDAOclass when the servlet is first created. The JDBC connection information will be retrieved from the context parameters of the Servlet. Because this method is only called once during the servlet's lifetime, it's appropriate to place the DAO instantiation code here:

public void init() {
   String jdbcURL = getServletContext().getInitParameter("jdbcURL");
   String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
   String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");
   bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);
}
You can also try this code with Online Java Compiler
Run Code

Next, we can see that this servlet can handle both GET and POST requests because the doPost() method calls the doGet() method, which takes care of everything:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
   String action = request.getServletPath();
   try {
       switch (action) {
       case "/new":
           showNewForm(request, response);
           break;
       case "/insert":
           insertBook(request, response);
           break;
       case "/delete":
           deleteBook(request, response);
           break;
       case "/edit":
           showEditForm(request, response);
           break;
       case "/update":
           updateBook(request, response);
           break;
       default:
           listBook(request, response);
           break;
       }
   } catch (SQLException ex) {
       throw new ServletException(ex);
   }
}
You can also try this code with Online Java Compiler
Run Code

The servlet invokes the correct methods based on the request URL (starts with /edit, /list, /new, etc.). We'll take a look at one way in particular:

private void listBook(HttpServletRequest request, HttpServletResponse response)
       throws SQLException, IOException, ServletException {
   List<Book> listBook = bookDAO.listAllBooks();
   request.setAttribute("listBook", listBook);
   RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
   dispatcher.forward(request, response);
}
You can also try this code with Online Java Compiler
Run Code

This method uses the DAO class to fetch all books from the database and then displays the results on the BookList.JSP page. The remainder methods follow a similar logic pattern.

Configuring Web.xml

We must configure the ControllerServlet's mapping in the web deployment descriptor web.xml file in order for it to intercept all requests. Replace the following code in the web.xml file in the WebContentWEB-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
   <display-name>Books Management Web Application</display-name>
   <context-param>
       <param-name>jdbcURL</param-name>
       <param-value>jdbc:mysql://localhost:3306/bookstore</param-value>
   </context-param>
   <context-param>
       <param-name>jdbcUsername</param-name>
       <param-value>root</param-value>
   </context-param>
   <context-param>
       <param-name>jdbcPassword</param-name>
       <param-value>P@ssw0rd</param-value>
   </context-param>
   <servlet>
       <servlet-name>ControllerServlet</servlet-name>
       <servlet-class>net.codejava.javaee.bookstore.ControllerServlet</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>ControllerServlet</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
   <error-page>
       <exception-type>java.lang.Exception</exception-type>
       <location>/Error.jsp</location>
   </error-page>
</web-app>

The <context-param> elements specify JDBC connection information for the DAO class (URL, username, and password).

For the ControllerServletclass, the <servlet> and <servlet-mapping> parts declare and specify URL mapping. The ‘/’ in the URL pattern denotes that this is the default servlet for all queries.

The <error> page components provide the error handling page for any type of exception (java.lang.Exception) that may occur throughout the application's lifetime.

Writing Error JSP page

Here’s the code of the Error.jsppage which simply shows the exception message:

<html>
<head>
<title>Error</title>
</head>
<body>
   <center>
       <h1>Error</h1>
       <h2><%=exception.getMessage() %><br/> </h2>
   </center>
</body>
</html>

When an error occurs, it appears as follows:

Error Page

Deploying and Testing the Application

So far, we've finished the project's code. It's time to put the app out there and see how it performs.

To access the Bookstore application, type the following URL into your browser:

http://localhost:8080/Bookstore

The list is empty for the first time since no books have been added yet:

HomePage

To begin adding a new book, click the hyperlink Add New Book:

Add New Book

Click Save after entering the book's details (title, author, and price). The application saves the book and displays the following list:

HomePage

You can edit and delete a specific book by clicking the Edit and Delete hyperlinks in this list.

That's how you make a basic Java web application using Servlet, JSP, JDBC, and MySQL.

Frequently Asked Questions

What is JSP?

Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent methods for building Web-based applications.

What are CRUD operations?

The four basic CRUD operations are Create, Read, Update and Delete.

How do CRUD operations work?

If we wish to make a new record, for example, we should use the HTTP action verb POST. The PUT verb should be used to update a record. In the same way, we should use the DELETE verb to delete a record.

How are CRUD operations related to HTTP requests?

The CRUD technique is a collection of user interface patterns that enable users to browse, search and modify data using computer-based forms and reports. CRUD is Create, Read, Update, and Delete, and it refers to the standardised use of HTTP action verbs. There are a few key verbs in HTTP.

How is a CRUD operation mapped with SQL Queries and HTTP methods?

The CRUD operations refer to all major functions that are implemented in relational database applications. Each letter of the CRUD can map to a SQL statement and HTTP methods.

Operation SQL HTTP verbs RESTful Web Service
Create INSERT PUT/POST POST
Read SELECT GET GET
Update UPDATE PUT/POST/PATCH PUT
Delete DELETE DELETE DELETE

 

Conclusion

We learned about the JSP framework. In this article, we learned about the various CRUD operations in detail. We also learned about the detailed example to demonstrate CRUD operations in JSP.

Recommended Readings:

What is Servlet

Why is Java Platform Independent 

Apart from this, you can also expand your knowledge by referring to these articles on Java and Web development.

For more information about backend development, get into the entire Backend web development course.

Do check out some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, etc. on Coding Ninjas Studio

Also Check out some of the amazing Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Basics of C, Basics of Java, etc. along with some Contests and Interview Experiences only on Coding Ninjas Studio

Happy Learning!

Live masterclass