使用jspModel2实现显示所有图书信息,已知数据库名为db_book,用户名和密码均为aa,图书数据表为tb_test,图书包含书名、作者和价格信息,具体要求如下:(1)BookDao中的queryAll方法,用与获取所有图书信息,返回结果为ArrayList<Book>; (2)Servlet文件ShowAllBooksServlet满用BookDao中的queryAll方法获数所有图书信息,并将信息保存到session中,ShowAllBooksServlet文件跳转到bookList.jsp (3)bookList.jsp文件,使用forEach标签获取图书信息,并显示,运行效果如下图所示 请给出BookDao、ShowAllBooksServlet、bookList.jsp三个文件的核心代码。
时间: 2023-03-14 14:30:13 浏览: 102
BookDao:public class BookDao {
private static final String DB_URL = "jdbc:mysql://localhost:3306/db_book";
private static final String USER_NAME = "aa";
private static final String PASSWORD = "aa"; public ArrayList<Book> queryAll() {
ArrayList<Book> bookList = new ArrayList<Book>();
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD); String sql = "SELECT * FROM tb_test";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString("name");
String author = resultSet.getString("author");
double price = resultSet.getDouble("price");
Book book = new Book(name, author, price);
bookList.add(book);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return bookList;
}
}ShowAllBooksServlet:public class ShowAllBooksServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BookDao bookDao = new BookDao();
ArrayList<Book> bookList = bookDao.queryAll();
req.getSession().setAttribute("bookList", bookList);
req.getRequestDispatcher("bookList.jsp").forward(req, resp);
}
}bookList.jsp:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
<h3>图书列表</h3>
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>书名</th>
<th>作者</th>
<th>价格</th>
</tr>
<c:forEach items="${session.bookList}" var="book">
<tr>
<td>${book.name}</td>
<td>${book.author}</td>
<td>${book.price}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
阅读全文