【问题标题】:Spring MVC, no data showing in my index.jspSpring MVC,我的 index.jsp 中没有显示数据
【发布时间】:2021-07-09 01:57:02
【问题描述】:

我正在通过在线学习来练习创建自己的 JDBC CRUD Web 应用程序......但是,当我尝试对其进行测试时,我的 index.jsp 中没有显示任何数据,并且我无法在我的代码中找到错误。我一遍又一遍地检查/修改我的代码,查看控制台是否有任何错误,但仍然没有任何反应。这让我犹豫是否要继续编写剩余的 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>

【问题讨论】:

    标签: java spring spring-mvc jsp model-view-controller


    【解决方案1】:

    我试图用这段代码再次审查编程......

    正如 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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 数据库中有数据是我在MySQL工作台中手动输入的。但是,在我的 JSP 页面上没有成功检索数据。我发布这个是因为我在 servlet 和 jsp 之间传递数据时可能遗漏了一些东西。
      • 您的数据已成功从您的 JSP 页面保存到数据库中?
      • 不,显然在表单中输入数据后,当我单击提交按钮时,它会显示带有时区的 HTTP 错误 500。 java.sql.SQLException:服务器时区值“马来半岛标准时间”无法识别或代表多个时区。如果您想利用时区支持,您必须配置服务器或 JDBC 驱动程序(通过 serverTimezone 配置属性)以使用更具体的时区值。
      • 我显然在时区错误上解决了这个问题,现在我的 JSP 页面中的数据已成功保存在数据库中,并且数据库中的记录已成功显示在 JSP 页面中。但是,当重新启动 Web 应用程序时,它不会自动在 JSP 页面中显示数据......我需要添加另一条记录来刷新并显示数据库中的所有数据。抱歉,我对此感到很困惑。
      猜你喜欢
      • 2013-03-27
      • 2013-02-24
      • 1970-01-01
      • 2014-05-09
      • 2015-09-08
      • 1970-01-01
      • 2017-12-20
      • 2021-10-14
      • 2014-02-07
      相关资源
      最近更新 更多