JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例

在本 Java 教程中,我们将帮助您了解编写基本 Java Web 应用程序的过程,该应用程序管理具有基本功能的书籍集合:列表、插入、更新、删除(或 CURD 操作 - 创建、更新、读取和删除)。该应用程序看起来像这样:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第1张图片

您将学习如何使用以下技术构建此应用程序:

  • Java Servlet 和 Java 服务器页面 (JSP)
  • JSP 标准标签库 (JSTL)
  • Java 数据库连接 (JDBC)
  • MySQL数据库
  • Apache Tomcat 服务器

我们使用 Eclipse IDE 和 Maven 来开发项目。

 

1. 创建 MySQL 数据库

为简单起见,我们只有一张桌子。执行以下 MySQL 脚本以创建名为Bookstore 的数据库和名为Book的表:

1
2
3
4
5
6
7
8
9
10
11
12
CREATE DATABASE 'Bookstore';
USE Bookstore;
 
CREATE TABLE `book` (
  `book_id` int(11) NOT NULL AUTO_INCREMENT,
  `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`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1

的结构如下:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第2张图片

您可以使用 MySQL 命令行客户端或 MySQL Workbench 工具来创建数据库。


 

 

2. 使用 Maven 创建 Eclipse 项目

在 Eclipse IDE 中,单击File > New > Dynamic Web Project以创建一个新的 Java 动态 Web 项目。将项目命名为书店:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第3张图片

请记住将Target runtime选择为Apache Tomcat v8.0,将Dynamic web module version选择为3.1(这是 Java servlet 版本)。

单击完成。然后将此项目转换为 Maven 项目,右键项目,选择Configure > Convert to Maven Project,如下图:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第4张图片

创建 Maven POM 文件需要输入信息,例如组 ID、工件 ID 等。然后在pom.xml 文件中添加以下依赖项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<dependencies>
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.1.0version>
        <scope>providedscope>
    dependency>
    <dependency>
        <groupId>javax.servlet.jspgroupId>
        <artifactId>javax.servlet.jsp-apiartifactId>
        <version>2.3.1version>
        <scope>providedscope>
    dependency>
    <dependency>
        <groupId>jstlgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.30version>
    dependency>
dependencies>

如您所见,这里的依赖项是针对 Servlet、JSP、JSTL 和 MySQL 连接器 Java(MySQL 的 JDBC 驱动程序)。

并且记得为项目创建一个 Java 包,这里我们使用包名net.codejava.javaee.bookstore

 

3. 编写模型类

接下来,使用以下代码创建一个名为Book.java的 Java 类来对数据库中的图书实体进行建模:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package net.codejava.javaee.bookstore;
 
/**
 * Book.java
 * This is a model class represents a book entity
 * @author www.codejava.net
 *
 */
public class Book {
    protected int id;
    protected String title;
    protected String author;
    protected float price;
 
    public Book() {
    }
 
    public Book(int id) {
        this.id = id;
    }
 
    public Book(int id, String title, String author, float price) {
        this(title, author, price);
        this.id = id;
    }
     
    public Book(String title, String author, float price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getAuthor() {
        return author;
    }
 
    public void setAuthor(String author) {
        this.author = author;
    }
 
    public float getPrice() {
        return price;
    }
 
    public void setPrice(float price) {
        this.price = price;
    }
}

如您所见,该类根据数据库中表book中的 4 列有 4 个字段:id、title、author 和 price。

 

4.编码DAO类

接下来,我们需要实现一个数据访问层 (DAO) 类,该类为数据库中的表book提供 CRUD(创建、读取、更新、删除)操作。这是BookDAO类的完整源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package net.codejava.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.ArrayList;
import java.util.List;
 
/**
 * AbstractDAO.java
 * This DAO class provides CRUD database operations for the table book
 * in the database.
 * @author www.codejava.net
 *
 */
public class BookDAO {
    private String jdbcURL;
    private String jdbcUsername;
    private String jdbcPassword;
    private Connection jdbcConnection;
     
    public BookDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {
        this.jdbcURL = jdbcURL;
        this.jdbcUsername = jdbcUsername;
        this.jdbcPassword = jdbcPassword;
    }
     
    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);
        }
    }
     
    protected void disconnect() throws SQLException {
        if (jdbcConnection != null && !jdbcConnection.isClosed()) {
            jdbcConnection.close();
        }
    }
     
    public boolean insertBook(Book book) throws SQLException {
        String sql = "INSERT INTO book (title, author, price) VALUES (?, ?, ?)";
        connect();
         
        PreparedStatement statement = jdbcConnection.prepareStatement(sql);
        statement.setString(1, book.getTitle());
        statement.setString(2, book.getAuthor());
        statement.setFloat(3, book.getPrice());
         
        boolean rowInserted = statement.executeUpdate() > 0;
        statement.close();
        disconnect();
        return rowInserted;
    }
     
    public List listAllBooks() throws SQLException {
        List listBook = new ArrayList<>();
         
        String sql = "SELECT * FROM book";
         
        connect();
         
        Statement statement = jdbcConnection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
         
        while (resultSet.next()) {
            int id = resultSet.getInt("book_id");
            String title = resultSet.getString("title");
            String author = resultSet.getString("author");
            float price = resultSet.getFloat("price");
             
            Book book = new Book(id, title, author, price);
            listBook.add(book);
        }
         
        resultSet.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 updateBook(Book book) throws SQLException {
        String sql = "UPDATE book SET title = ?, author = ?, price = ?";
        sql += " WHERE book_id = ?";
        connect();
         
        PreparedStatement statement = jdbcConnection.prepareStatement(sql);
        statement.setString(1, book.getTitle());
        statement.setString(2, book.getAuthor());
        statement.setFloat(3, book.getPrice());
        statement.setInt(4, book.getId());
         
        boolean rowUpdated = statement.executeUpdate() > 0;
        statement.close();
        disconnect();
        return rowUpdated;     
    }
     
    public Book getBook(int id) throws SQLException {
        Book book = null;
        String sql = "SELECT * FROM book WHERE book_id = ?";
         
        connect();
         
        PreparedStatement statement = jdbcConnection.prepareStatement(sql);
        statement.setInt(1, id);
         
        ResultSet resultSet = statement.executeQuery();
         
        if (resultSet.next()) {
            String title = resultSet.getString("title");
            String author = resultSet.getString("author");
            float price = resultSet.getFloat("price");
             
            book = new Book(id, title, author, price);
        }
         
        resultSet.close();
        statement.close();
         
        return book;
    }
}

如您所见,JDBC 连接信息是通过其构造函数注入到此类的。以下方法适用于 CRUD 操作:

  • 创建:insertBook(Book) - 这会在表book中插入一个新行。
  • 读取:listAllBooks() - 这会检索所有行;和getBook(id) - 根据主键值 (ID) 返回特定行。
  • 更新:updateBook(Book) - 这会更新数据库中的现有行。
  • 删除:deleteBook(Book) - 这会根据主键值 (ID) 删除数据库中的现有行。

有关使用 JDBC 进行 CRUD 操作的详细说明,请参阅 JDBC 教程:SQL 插入、选择、更新和删除示例。

 

5.编写图书列表JSP页面

接下来,创建一个 JSP 页面来显示数据库中的所有书籍。以下是项目中WebContent目录下BookList.jsp页面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Books Store Applicationtitle>
head>
<body>
    <center>
        <h1>Books Managementh1>
        <h2>
            <a href="/new">Add New Booka>
               
            <a href="/list">List All Booksa>
             
        h2>
    center>
    <div align="center">
        <table border="1" cellpadding="5">
            <caption><h2>List of Booksh2>caption>
            <tr>
                <th>IDth>
                <th>Titleth>
                <th>Authorth>
                <th>Priceth>
                <th>Actionsth>
            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=value='${book.id}' />">Edita>
                            
                        <a href="/delete?id=value='${book.id}' />">Deletea>                     
                    td>
                tr>
            c:forEach>
        table>
    div>   
body>
html>

在这个 JSP 页面中,我们使用 JSTL 来显示来自数据库的表book的记录。listBook对象将从我们稍后创建的 servlet 传递。

运行时,此页面如下所示:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第5张图片

如您所见,在此页面的顶部菜单中有两个超链接,用于创建新书(添加新书)和显示所有书(列出所有书)。此外,对于每本书,都有两个用于编辑 ( Edit ) 和删除 ( Delete ) 的链接。

 

6.写书表单JSP页面

接下来,我们创建一个 JSP 页面来创建一本名为BookForm.jsp的新书。这是它的完整源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Books Store Applicationtitle>
head>
<body>
    <center>
        <h1>Books Managementh1>
        <h2>
            <a href="/new">Add New Booka>
               
            <a href="/list">List All Booksa>
             
        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="value='${book.id}' />" />
                c:if>           
            <tr>
                <th>Title: th>
                <td>
                    <input type="text" name="title" size="45"
                            value="value='${book.title}' />"
                        />
                td>
            tr>
            <tr>
                <th>Author: th>
                <td>
                    <input type="text" name="author" size="45"
                            value="value='${book.author}' />"
                    />
                td>
            tr>
            <tr>
                <th>Price: th>
                <td>
                    <input type="text" name="price" size="5"
                            value="value='${book.price}' />"
                    />
                td>
            tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="Save" />
                td>
            tr>
        table>
        form>
    div>   
body>
html>

此页面将用于创建新书和编辑现有书籍。在编辑模式下,servlet 将向请求传递一个 Book 对象,我们使用 JSTL 的标记来确定该对象是否可用。如果可用(非空)表单处于编辑模式,否则处于创建模式。

运行时,此页面显示如下新表单:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第6张图片

在编辑模式下:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第7张图片

我们将在下一节中了解如何根据用户的请求将 DAO 类与 JSP 页面连接起来:创建 servlet 类。

 

7. 编码控制器Servlet类

现在,最困难但最有趣的部分是实现一个 Java Servlet,它充当页面控制器来处理来自客户端的所有请求。我们先来看代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package net.codejava.javaee.bookstore;
 
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * ControllerServlet.java
 * This servlet acts as a page controller for the application, handling all
 * requests from the user.
 * @author www.codejava.net
 */
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 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");
 
    }
}

首先,查看init()方法,该方法在第一次实例化 servlet 时实例化BookDAO类的实例。JDBC 连接信息将从 Servlet 的上下文参数中读取。该方法在 servlet 的生命周期中只调用一次,因此将 DAO 实例化代码放在这里是合理的:

1
2
3
4
5
6
7
8
public void init() {
    String jdbcURL = getServletContext().getInitParameter("jdbcURL");
    String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
    String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");
 
    bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);
 
}

接下来,我们可以看到这个 servlet 同时处理GETPOST请求,因为doPost()方法调用了处理所有请求的doGet() :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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);
    }
}

根据请求 URL(以 /edit、/list、/new 等开头),servlet 调用相应的方法。在这里,我们以一种方法为例:

1
2
3
4
5
6
7
private void listBook(HttpServletRequest request, HttpServletResponse response)
        throws SQLException, IOException, ServletException {
    List listBook = bookDAO.listAllBooks();
    request.setAttribute("listBook", listBook);
    RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
    dispatcher.forward(request, response);
}

该方法使用 DAO 类从数据库中检索所有书籍,然后转发到BookList.jsp页面以显示结果。其余方法也实现了类似的逻辑。

我推荐你阅读这本著名的 Servlet and JSP 书籍来掌握 Java servlet 和 JSP。

 

8.配置Web.xml

为了让ControllerServlet 拦截所有请求,我们必须在 web 部署描述符web.xml 文件中配置它的映射。打开WebContent\WEB-INF 目录下的 web.xml 文件并使用以下代码更新它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>Books Management Web Applicationdisplay-name>
 
    <context-param>
        <param-name>jdbcURLparam-name>
        <param-value>jdbc:mysql://localhost:3306/bookstoreparam-value>
    context-param>
 
    <context-param>
        <param-name>jdbcUsernameparam-name>
        <param-value>rootparam-value>
    context-param>
 
    <context-param>
        <param-name>jdbcPasswordparam-name>
        <param-value>P@ssw0rdparam-value>
    context-param>
 
    <servlet>
        <servlet-name>ControllerServletservlet-name>
        <servlet-class>net.codejava.javaee.bookstore.ControllerServletservlet-class>
    servlet>
 
    <servlet-mapping>
        <servlet-name>ControllerServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
 
    <error-page>
        <exception-type>java.lang.Exceptionexception-type>
        <location>/Error.jsplocation>
    error-page>
web-app>

 如您所见,元素为 DAO 类指定 JDBC 连接信息(URL、用户名和密码)。

servlet>元素声明并指定ControllerServlet类的 URL 映射。URL 模式/表示这是处理所有请求的默认 servlet。

页面元素为应用程序生命周期中可能发生的所有类型的异常( java.lang.Exception )指定错误处理页面。

有关 Java Web 应用程序中的错误处理的详细信息,请阅读本教程。

 

9.编写错误JSP页面

这是Error.jsp页面的代码,它只显示异常消息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Errortitle>
head>
<body>
    <center>
        <h1>Errorh1>
        <h2><%=exception.getMessage() %><br/> h2>
    center>
body>
html>

发生错误时看起来像这样:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第8张图片

 

10. 部署和测试应用程序

至此我们已经完成了项目的代码。是时候部署和测试应用程序以了解它是如何工作的了。如果您不知道如何在 Eclipse 中添加 Apache Tomcat 服务器,请遵循本教程。

在 Web 浏览器中键入以下 URL 以访问 Bookstore 应用程序:

http://localhost:8080/书店

第一次,列表是空的,因为还没有任何书籍:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第9张图片

单击超链接添加新书开始添加新书:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第10张图片

输入图书信息(书名、作者和价格)并点击保存。应用程序保存图书并显示列表,如下图所示:

JSP Servlet JDBC MySQL 创建读取更新删除 (CRUD) 示例_第11张图片

在此列表中,您可以单击编辑删除超链接来编辑和删除特定书籍。

这就是使用 Serlvet、JSP、JDBC 和 MySQL 构建简单的 Java Web 应用程序的方式。我们希望本教程对您有所帮助,您可以在下面的附件部分下载整个项目。
 

附件:
书店.zip 【Eclipse-Maven项目】 22 KB

你可能感兴趣的:(java,maven,eclipse)