Spring MVC,我的 index.jsp 中没有显示数据

Spring MVC, no data showing in my index.jsp

我正在练习通过在线学习创建自己的 JDBC CRUD 网络应用程序...但是,当我尝试对其进行测试时,我的 index.jsp 中没有显示任何数据,我无法在我的代码中找到错误。我 checked/reworked 我的代码一遍又一遍,查看控制台是否有任何错误,但仍然没有任何反应。这让我犹豫是否要继续为剩余的 CRUD 操作编码。

我遇到了困难,因为我认为我正确地将 jsp 中的 listBooks 对象传递给了 servlet,还是没有?

这是我的控制器 Servlet:

 @WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private BookDAO bkDAO;
    
    public void init() {
        String jdbcURL = getServletContext().getInitParameter("jdbcURL");
        String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
        String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");
        
        bkDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);
    }
   
    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":
                break;
            case "/edit":
                break;
            case "/update":
                break;
                
            default:
                bookcollection(request, response);
                break;
            }
            
        }catch(SQLException e) {
            throw new ServletException(e);
        }
        
        
    }
    
    private void bookcollection(HttpServletRequest request, HttpServletResponse response) 
        throws SQLException, IOException, ServletException{
            //list object from the Data Access Object
            List<BookCollectionModel> listBooks = bkDAO.listBooks();
            request.setAttribute("listBooks", listBooks);
            RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);
        }
    
    private void showNewForm (HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException, ServletException{
        RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
        dispatcher.forward(request, response);
    }
    
    private void insertBook (HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException, ServletException{
        int bookID = Integer.parseInt(request.getParameter("bookID"));
        String title  = request.getParameter("title");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String edition = request.getParameter("edition");
        int pages = Integer.parseInt(request.getParameter("pages"));
        int year = Integer.parseInt(request.getParameter("year"));
        int price = Integer.parseInt(request.getParameter("price"));
        
        BookCollectionModel newBook = new BookCollectionModel(bookID, title, author, publisher, edition, pages, year, price);
        bkDAO.insertBook(newBook);
        
        response.sendRedirect("list");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

我的数据访问对象代码:

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 List<BookCollectionModel> listBooks() throws SQLException{
        List<BookCollectionModel> listBooks = new ArrayList<>();
    
    String sql = "SELECT * FROM bookinformation ORDER BY title";    
    

    //create statement for connection
    Statement statement = jdbcConnection.createStatement();
    //result set contains the records retrieved on executing the SQL.
    ResultSet resultSet = statement.executeQuery(sql);
    
    //looping all the records on the result set
    while(resultSet.next()) {
        int id = resultSet.getInt("bookID");
        String title = resultSet.getString("title");
        String author = resultSet.getString("author");
        String publisher = resultSet.getString("publisher");
        String edition = resultSet.getString("edition");
        int pages = resultSet.getInt("pages");
        int year = resultSet.getInt("year");
        int price = resultSet.getInt("price");
        
        BookCollectionModel books = new BookCollectionModel(id, title, author, publisher, edition, pages, year, price);
        listBooks.add(books);
    }
    resultSet.close();
    statement.close();
    disconnect();
    return listBooks;
    }
    
    public boolean insertBook (BookCollectionModel newBook) throws SQLException{
        String sql = "INSERT INTO bookinformation (bookID, title, author, publisher, edition, pages, year, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        connect();
        
        PreparedStatement statement = jdbcConnection.prepareStatement(sql);
        statement.setInt(1, newBook.getBookID());
        statement.setString(2, newBook.getTitle());
        statement.setString(3, newBook.getAuthor());
        statement.setString(4, newBook.getPublisher());
        statement.setString(5, newBook.getEdition());
        statement.setInt(6, newBook.getPages());
        statement.setInt(7, newBook.getYear());
        statement.setInt(8, newBook.getPrice());
        
        boolean rowInserted = statement.executeUpdate() > 0;
        statement.close();
        disconnect();
        return rowInserted;
    }
}

这是我的index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Book Collection DB</title>
</head>
<body>
    <center>
        <h1>Book Management</h1>
        <h2>
            <a href="/BookCollectionJDBC/new">Add New Account</a>
            &nbsp;&nbsp;&nbsp;
            <a href="/BookCollectionJDBC/list">List All Accounts</a>
        </h2>
        
    <div align="center">
        <table border="1" cellpadding="5">
            <caption><h2>List of Books</h2>
            <tr>
                <th>Book ID</th>
                <th>Title</th>
                <th>Author</th>
                <th>Publisher</th>
                <th>Edition</th>
                <th>Pages</th>
                <th>Year</th>
                <th>Price</th>
            </tr>
        <c:forEach var="books" items="${listBooks}">
            <tr>
                <td><c:out value="${books.bookID}"></c:out></td>
                <td><c:out value="${books.title}"></c:out></td>
                <td><c:out value="${books.author}"></c:out></td>
                <td><c:out value="${books.publisher}"></c:out></td>
                <td><c:out value="${books.edition}"></c:out></td>
                <td><c:out value="${books.pages}"></c:out></td>
                <td><c:out value="${books.year}"></c:out></td>
                <td><c:out value="${books.price}"></c:out></td>
                
                <td>
                    <a href="/BookCollectionJDBC/edit?id=<c:out value='${books.bookID}'/>">Edit</a>
                        &nbsp;&nbsp;&nbsp;
                    <a href="/BookCollectionJDBC/delete?id=<c:out value='${books.bookID}'/>">Delete</a>
                
                </td>
            </tr>
        </c:forEach>        
        </table>
    
    </div>
        
</body>
</html>

这是我的 web.xml

<?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_4_0.xsd" version="4.0">
  <display-name>BookCollectionJDBC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <context-param>
    <param-name>jdbcURL</param-name>
    <param-value>jdbc:mysql://localhost:3306/bookcollectiondb</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>123456</param-value>
  </context-param>  
  
  <servlet>
    <servlet-name>BookServlet</servlet-name>
    <servlet-class>com.model.BookServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BookServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

您的代码看起来不错。您可以在 MySQL workbench 中检查您的数据库是否存储了数据,或者您可以手动将一条记录放入您的一个表中并检查数据是否在您的 JSP 页面上成功检索或不是吗?

我试着用这段代码再次复习编程...

正如 kameshrsr 所说,代码很好。我只是错过了在我的数据访问对象代码中调用 connect()。

这是我之前的代码:

 public List<BookCollectionModel> listBooks() throws SQLException{
            List<BookCollectionModel> listBooks = new ArrayList<>();
    
    String sql = "SELECT * FROM bookinformation ORDER BY title";    
    

    //create statement for connection
    Statement statement = jdbcConnection.createStatement();
    //result set contains the records retrieved on executing the SQL.
    ResultSet resultSet = statement.executeQuery(sql);

应该是:

public List<BookCollectionModel> listBooks() throws SQLException{
                List<BookCollectionModel> listBooks = new ArrayList<>();
    
    String sql = "SELECT * FROM bookinformation ORDER BY title";    
        
    connect();   //I missed this part

    //create statement for connection
    Statement statement = jdbcConnection.createStatement();
    //result set contains the records retrieved on executing the SQL.
    ResultSet resultSet = statement.executeQuery(sql);