SoFunction
Updated on 2025-03-09

jsp+servlet+jdbc implements the addition, deletion, modification and search of databases

1. A brief introduction to JSP and Servlets

1. Introduction to Servlet and JSP:

There are two main technologies used when Java develops web applications, namely Servlet and JSP. Servlet is a Java program executed on the server side. A program called a Servlet container (actually a server) is responsible for executing Java programs, while JSP (Java Server Page) is a page, which is executed by the JSP container.

2. The difference between Servlet and JSP:

Servlets are mainly Java programs, and functions are required to output HTML code, that is, HTML is embedded in Java; while JSP is mainly HTML pages. When Java code is needed, Java code is directly inserted into the page, that is, Java is embedded in HTML.

3. MVC model

The MVC model is a way to separate data, logic processing, and user interface.

1) M (Model, model): used for data processing and logical processing

2), V (View, view): used to display the user interface

3) C (Controller, controller): Control the logical direction and screen according to the client's request

In Java, the three parts of MVC correspond to JavaBeans, JSP and Servlet respectively

1), M = JavaBeans: used to pass data and have logical processing related to data.

2), V = JSP: Receive data from Model and generate HTML

3), C = Servlet: Receive HTTP requests and control Model and View

4. For jdbc connection, please refer to the article:Click to open the link

2. Code demonstration, implementing the addition, deletion and modification functions of the book

1. Environment configuration

myeclipse+tomcat+MySQL

2. Bean class in Book

package ;  
public class Book { 
  // serial number  private int id; 
  // Book name  private String name; 
  // price  private double price; 
  // quantity  private int bookCount; 
  // author  private String author; 
 
  public int getId() { 
    return id; 
  } 
 
  public void setId(int id) { 
     = id; 
  } 
 
  public String getName() { 
    return name; 
  } 
 
  public void setName(String name) { 
     = name; 
  } 
 
  public double getPrice() { 
    return price; 
  } 
 
  public void setPrice(double price) { 
     = price; 
  } 
 
  public int getBookCount() { 
    return bookCount; 
  } 
 
  public void setBookCount(int bookCount) { 
     = bookCount; 
  } 
 
  public String getAuthor() { 
    return author; 
  } 
 
  public void setAuthor(String author) { 
     = author; 
  } 
 
} 

3. Servlet class

1)、

package ;  
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
 
/** 
 * Servlet implementation class FindServlet 
 */ 
public class FindServlet extends HttpServlet { 
  private static final long serialVersionUID = 1L; 
 
  /** 
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    try { 
      // Load the database driver and register it to the driver manager      (""); 
      // Database connection string      String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8"; 
      // Database username      String username = "root"; 
      // Database Password      String password = ""; 
      // Create a Connection connection      Connection conn = (url, username, 
          password); 
      // SQL statements that add book information      String sql = "select * from tb_books"; 
      // Get Statement      Statement statement = (); 
 
      ResultSet resultSet = (sql); 
 
      List<Book> list = new ArrayList<Book>(); 
      while (()) { 
 
        Book book = new Book(); 
        (("id")); 
        (("name")); 
        (("price")); 
        (("bookCount")); 
        (("author")); 
        (book); 
 
      } 
      ("list", list); 
      (); 
      (); 
      (); 
 
    } catch (Exception e) { 
      (); 
    } 
 
    ("book_list.jsp") 
        .forward(request, response); 
 
  } 
 
  /** 
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
    doGet(request, response); 
  } 
 
} 

2) Class

package ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
 
/** 
 * Servlet implementation class UpdateServlet 
 */ 
public class UpdateServlet extends HttpServlet { 
  private static final long serialVersionUID = 1L; 
 
  /** 
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    int id = (("id")); 
    int bookCount = (("bookCount")); 
    try { 
      // Load the database driver and register it to the driver manager      (""); 
      // Database connection string      String url = "jdbc:mysql://localhost:3306/db_book"; 
      // Database username      String username = "root"; 
      // Database Password      String password = ""; 
      // Create a Connection connection      Connection conn = (url, username, 
          password); 
      // Update SQL statements      String sql = "update tb_books set bookcount=? where id=?"; 
      // Get PreparedStatement      PreparedStatement ps = (sql); 
      // Assign the first parameter in the SQL statement      (1, bookCount); 
      // Assign the second parameter in the SQL statement      (2, id); 
      // Perform update operation      (); 
      // Close PreparedStatement      (); 
      // Close Connection      (); 
    } catch (Exception e) { 
      (); 
    } 
    // Redirect to FindServlet    ("FindServlet"); 
 
  } 
 
  /** 
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
    doGet(request, response); 
  } 
 
} 

3) DeleteServlet class

package ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
/** 
 * Servlet implementation class DeleteServlet 
 */ 
public class DeleteServlet extends HttpServlet { 
  private static final long serialVersionUID = 1L; 
 
  /** 
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    int id = (("id")); 
    try { 
// // Load the database driver and register it to the driver manager//     (""); 
// // Database connection string//     String url = "jdbc:mysql://localhost:3306/db_book"; 
// // Database username//     String username = "root"; 
// // Database Password//     String password = ""; 
// // Create a Connection connection//     Connection conn = (url, username, 
//         password); 
// // SQL statement to delete book information//     String sql = "delete from tb_books where id=?"; 
// // Get PreparedStatement//     PreparedStatement ps = (sql); 
// // Assign the first placeholder in the SQL statement//     (1, id); 
// // Perform update operation//     (); 
// // Close PreparedStatement//     (); 
// // Close Connection//     (); 
      BookJdbcDao bookDao=new BookJdbcDao(); 
      Connection conn=().getConnection(); 
      (conn,id); 
       
    } catch (Exception e) { 
      (); 
    } 
    // Redirect to FindServlet    ("FindServlet"); 
  } 
 
  /** 
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
   *   response) 
   */ 
  protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
    doGet(request, response); 
  } 
 
} 

4. Servlet access url mapping configuration:

Since the client accesses resources in the web server through URL addresses, if the servlet program wants to be accessed by the outside world, it must map the servlet program to a URL address. This work is done in the file using the <servlet> element and the <servlet-mapping> element. The <servlet> element is used to register the servlet, which contains two main child elements: <servlet-name> and <servlet-class>, which are used to set the registration name of the servlet and the complete class name of the servlet respectively.

A <servlet-mapping> element is used to map an external access path to a registered Servlet. It contains two child elements: <servlet-name> and <url-pattern>, which are used to specify the registration name of the Servlet and the external access path of the Servlet. In addition, the same Servlet can be mapped to multiple URLs, that is, the setting value of the <servlet-name> child element of multiple <servlet-mapping> elements can be the registration name of the same Servlet.

eg: in the above example

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http:///2001/XMLSchema-instance" xmlns="/xml/ns/javaee" xmlns:web="/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd"  version="2.5"> 
 <display-name>JdbcConnection</display-name> 
 <welcome-file-list> 
  <welcome-file></welcome-file> 
  <welcome-file></welcome-file> 
  <welcome-file></welcome-file> 
  <welcome-file></welcome-file> 
  <welcome-file></welcome-file> 
  <welcome-file></welcome-file> 
 </welcome-file-list> 
 <servlet> 
  <description></description> 
  <display-name>FindServlet</display-name> 
  <servlet-name>FindServlet</servlet-name> 
  <servlet-class></servlet-class> 
 </servlet> 
 <servlet-mapping> 
  <servlet-name>FindServlet</servlet-name> 
  <url-pattern>/FindServlet</url-pattern> 
 </servlet-mapping> 
 <servlet> 
  <description></description> 
  <display-name>UpdateServlet</display-name> 
  <servlet-name>UpdateServlet</servlet-name> 
  <servlet-class></servlet-class> 
 </servlet> 
 <servlet-mapping> 
  <servlet-name>UpdateServlet</servlet-name> 
  <url-pattern>/UpdateServlet</url-pattern> 
 </servlet-mapping> 
 <servlet> 
  <description></description> 
  <display-name>DeleteServlet</display-name> 
  <servlet-name>DeleteServlet</servlet-name> 
  <servlet-class></servlet-class> 
 </servlet> 
 <servlet-mapping> 
  <servlet-name>DeleteServlet</servlet-name> 
  <url-pattern>/DeleteServlet</url-pattern> 
 </servlet-mapping> 
</web-app> 

5. jsp page

1) The main interface of the web page

&lt;%@page import=""%&gt; 
&lt;%@page import=""%&gt; 
&lt;%@page import=""%&gt; 
&lt;%@ page language="java" contentType="text/html; charset=utf-8" 
  pageEncoding="utf-8"%&gt; 
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/"&gt; 
&lt;html&gt; 
&lt;head&gt; 
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; 
&lt;title&gt;Add book information&lt;/title&gt; 
 
&lt;script type="text/javascript"&gt; 
  function check(form) { 
    with (form) { 
      if ( == "") { 
        alert("The book name cannot be empty"); 
        return false; 
      } 
 
      if ( == "") { 
        alert("Book prices cannot be empty"); 
        return false; 
      } 
 
      if ( == "") { 
        alert("The author cannot be empty"); 
        return false; 
      } 
 
    } 
  } 
&lt;/script&gt; 
 
&lt;/head&gt; 
 
 
&lt;body&gt; 
 
&lt;form action="" method="post" onsubmit="check(this)"&gt; 
  &lt;table align="center" width="450"&gt; 
    &lt;tr&gt; 
      &lt;td align="center" colspan="2"&gt; 
        &lt;h2&gt;Add book information&lt;/h2&gt; 
        &lt;hr&gt; 
      &lt;/td&gt; 
    &lt;/tr&gt; 
 
    &lt;tr&gt; 
      &lt;td align="right"&gt;Book Name:&lt;/td&gt; 
      &lt;td&gt;&lt;input type="text" name="name"&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
 
    &lt;tr&gt; 
      &lt;td align="right"&gt;price grid:&lt;/td&gt; 
      &lt;td&gt;&lt;input type="text" name="price"&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
 
    &lt;tr&gt; 
      &lt;td align="right"&gt;number quantity:&lt;/td&gt; 
      &lt;td&gt;&lt;input type="text" name="bookCount" /&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
 
    &lt;tr&gt; 
      &lt;td align="right"&gt;do Those:&lt;/td&gt; 
      &lt;td&gt;&lt;input type="text" name="author" /&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
    &lt;tr&gt; 
      &lt;td align="center" colspan="2"&gt;&lt;input type="submit" value="Add to"&gt; 
      &lt;/td&gt; 
    &lt;/tr&gt; 
  &lt;/table&gt; 
&lt;/form&gt; 
 
&lt;h2 align="center"&gt; 
  &lt;a href="FindServlet"&gt;Query book information&lt;/a&gt; 
&lt;/h2&gt; 
 
&lt;/body&gt; 
&lt;/html&gt; 

2) Display page after successful or failed book addition

&lt;%@ page language="java" contentType="text/html; charset=utf-8" 
  pageEncoding="utf-8"%&gt; 
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/"&gt; 
 
&lt;%@page import=""%&gt; 
&lt;%@page import=""%&gt; 
&lt;%@page import=""%&gt; 
&lt;html&gt; 
&lt;head&gt; 
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; 
&lt;title&gt;Add results&lt;/title&gt; 
&lt;/head&gt; 
&lt;body&gt; 
  &lt;% 
    ("utf-8"); 
  %&gt; 
  &lt;jsp:useBean  class=""&gt;&lt;/jsp:useBean&gt; 
  &lt;jsp:setProperty property="*" name="book" /&gt; 
  &lt;% 
    try { 
      // Load the database driver and register it to the driver manager      (""); 
      // Database connection string      String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&amp;characterEncoding=utf-8"; 
      // Database username      String username = "root"; 
      // Database Password      String password = ""; 
      // Create a Connection connection      Connection conn = (url, username, 
          password); 
      // SQL statements that add book information      String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)"; 
      // Get PreparedStatement      PreparedStatement ps = (sql); 
      // Assign the first parameter in the SQL statement      (1, ()); 
      // Assign the second parameter in the SQL statement      (2, ()); 
      // Assign the third parameter in the SQL statement      (3, ()); 
      // Assign the 4th parameter in the SQL statement      (4, ()); 
      // Perform an update operation to return the number of rows affected      int row = (); 
      // Determine whether the update is successful      if (row &gt; 0) { 
        // Update to output information        ("Added successfully" + row + "Stuffed data!"); 
      } 
      // Close PreparedStatement and release resources      (); 
      // Close Connection and release resources      (); 
    } catch (Exception e) { 
      ("The book information was added failed!"); 
      (); 
    } 
  %&gt; 
  &lt;br&gt; 
  &lt;a href=""&gt;return&lt;/a&gt; 
&lt;/body&gt; 
&lt;/html&gt; 

3) book_list.jsp Find the display page of all book information and display it in a table form.

&lt;!--&lt;%@page import=""%&gt;--&gt; 
&lt;%@ page language="java" contentType="text/html; charset=utf-8" 
  pageEncoding="utf-8"%&gt; 
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/"&gt; 
 
&lt;%@page import=""%&gt; 
&lt;%@page import=""%&gt; 
&lt;html&gt; 
&lt;head&gt; 
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; 
&lt;title&gt;All book information&lt;/title&gt; 
&lt;style type="text/css"&gt; 
td { 
  font-size: 12px; 
} 
 
h2 { 
  margin: 0px 
} 
&lt;/style&gt; 
&lt;script type="text/javascript"&gt; 
  function check(form) { 
    with (form) { 
      if ( == "") { 
        alert("Please enter the update quantity!"); 
        return false; 
      } 
      if (isNaN()) { 
        alert("Error in format!"); 
        return false; 
      } 
      return true; 
    } 
  } 
&lt;/script&gt; 
 
 
&lt;/head&gt; 
&lt;body&gt; 
  &lt;table align="center" width="450" border="1" height="180" 
    bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1"&gt; 
    &lt;tr bgcolor="white"&gt; 
      &lt;td align="center" colspan="7"&gt; 
        &lt;h2&gt;All book information&lt;/h2&gt; 
      &lt;/td&gt; 
    &lt;/tr&gt; 
    &lt;tr align="center" bgcolor="#e1ffc1"&gt; 
      &lt;td&gt;&lt;b&gt;ID&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;Book Name&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;price&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;quantity&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;author&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;Revise&lt;/b&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;b&gt;delete&lt;/b&gt;&lt;/td&gt; 
    &lt;/tr&gt; 
    &lt;% 
      // Get a collection of book information      List&lt;Book&gt; list = (List&lt;Book&gt;) ("list"); 
      // Determine whether the set is valid      if (list == null || () &lt; 1) { 
        ("No data!"); 
      } else { 
        // traverse data in the book collection        for (Book book : list) { 
    %&gt; 
    &lt;tr align="center" bgcolor="white"&gt; 
      &lt;td&gt;&lt;%=()%&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;%=()%&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;%=()%&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;%=()%&gt;&lt;/td&gt; 
      &lt;td&gt;&lt;%=()%&gt;&lt;/td&gt; 
      &lt;td &gt; 
        &lt;form style="align:center; background-color: gray" action="UpdateServlet" method="post" 
          onsubmit="return check(this);"&gt; 
           &lt;input type="hidden" name="id" value="&lt;%=()%&gt;"&gt; &lt;input 
            type="text" name="bookCount" size="3"&gt; 
           &lt;input type="submit" value="Modify quantity"&gt; 
        &lt;/form&gt; 
      &lt;/td&gt; 
      &lt;td&gt; 
      &lt;a href="DeleteServlet?id=&lt;%=()%&gt;"&gt;delete&lt;/a&gt; 
      &lt;/td&gt; 
 
 
    &lt;/tr&gt; 
    &lt;% 
      } 
      } 
    %&gt; 
  &lt;/table&gt; 
  &lt;h2 align="center"&gt; 
    &lt;a href=""&gt;Return to the page to add book information&lt;/a&gt; 
  &lt;/h2&gt; 
 
&lt;/body&gt; 
&lt;/html&gt; 

6. JDBC simple encapsulation

1) Factory

package ; 
 
import ; 
import ; 
import ; 
 
public class ConnectionFactory { 
   
  private String driverClassName = ""; 
  private String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8"; 
  private String userName = "root"; 
  private String password = ""; 
   
  private static ConnectionFactory connectionFactory=null; 
 
  private ConnectionFactory() { 
     
    try { 
      (driverClassName); 
    } catch (ClassNotFoundException e) { 
      (); 
    } 
  } 
   
  public Connection getConnection() throws SQLException 
  { 
    return (url, userName, password); 
     
  } 
   
  public static ConnectionFactory getInstance() 
  {   
    if (null==connectionFactory) { 
      connectionFactory=new ConnectionFactory(); 
    } 
    return connectionFactory; 
     
  } 
} 

2) Database operation encapsulation class

package ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
 
public class BookJdbcDao { 
   
  private PreparedStatement ptmt = null; 
  private ResultSet rs = null; 
 
  public BookJdbcDao() { 
  } 
   
   
  public void findAll(Connection conn) throws SQLException 
  { 
    //to do 
     
  } 
   
  public void delete(Connection conn, int id) throws SQLException 
  { 
    String sql = "delete from tb_books where id=?"; 
    try{ 
      ptmt = (sql); 
      // Assign the first placeholder in the SQL statement      (1, id); 
      // Perform update operation      (); 
       
    }finally{ 
      if (null!=ptmt) { 
        (); 
      } 
       
      if (null!=conn) { 
        (); 
      } 
       
    } 
     
  } 
   
  public void update(Connection conn, int id ,int bookcount) throws SQLException 
  { 
    //to do 
     
  } 
   
 
} 

Source code download link

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.