我正在写我的第一个更大的应用程序,但有一个问题,下面的代码:
初始化数据库
public void requestInitialized(ServletRequestEvent arg0) {
EntityManager em = DBConfig.createEntityManager();
BooksDAO booksDAO = new BooksDAO(em);
CategoryDAO categoriesDAO = new CategoryDAO(em);
ServletRequest req = arg0.getServletRequest();
req.setAttribute("booksDao", booksDAO);
req.setAttribute("categoriesDao", categoriesDAO);
}
BooksDAO.java
EntityManager em = DBConfig.createEntityManager();
public BooksDAO(EntityManager em) {
this.em = em;
}
public List<Books> getBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
List<Books> booksByCategory = q.getResultList();
return booksByCategory;
}
booksCategoryServlet.java
@WebServlet("/booksCategory")
public class booksCategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String category = request.getParameter("category");
if (category != null) {
BooksDAO dao = (BooksDAO) request.getAttribute("booksDao");
List<Books> booksByCategory = dao.getBooksByCategory(category);
request.setAttribute("booksByCategory", booksByCategory);
request.getRequestDispatcher("/booksCategory.jsp").forward(request, response);
} else
response.sendRedirect(request.getContextPath() + "/");
}
bookCategory.jsp
<c:forEach var="book" items="${booksDao.booksByCategory}">
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.description}</td>
<td>${book.category}</td>
<td>${book.year}</td>
<td><a href="bookDetails?id=${book.id}">show details</a></td>
</tr>
</c:forEach>
index.jsp
<c:forEach var="category" items="${categoriesDao.categories}">
<a href="booksCategory?category=${category}"><li>${category}</li></a>
</c:forEach>
在索引页面中,我列出了类别,当我要转到选择的类别并显示该类别的书籍时,出现此异常:
org.apache.jasper.el.JspPropertyNotFoundException:/booksCategory.jsp(40,4)'$ {booksDao.booksByCategory}'属性'booksByCategory'在DAO.BooksDAO类型上找不到
有人可以告诉我我做错了什么吗?
最佳答案
您正在调用一种方法,以为您正在调用实际对象。
我将在List<Books>
中创建一个DAOBooks
对象,并将其与请求一起发送到JSP。
解
DAO书籍
EntityManager em = DBConfig.createEntityManager();
List<Books> booksByCategory = new ArrayList<>(); // Or whatever list type you need.
public BooksDAO(EntityManager em) {
this.em = em;
}
public void setBooksByCategory(String category) {
Query q = this.em.createQuery("SELECT b FROM Books b WHERE b.category = :category ", Books.class).setParameter("category", category);
booksByCategory = q.getResultList();
}
public List<Books> getBooksByCategory(){
return booksByCategory;
}
在你的
JSP
<c:forEach var="book" items="${booksByCategory}">
直接引用
List<Books>
对象,因为它是您通过请求发送的对象。编辑
尝试使用不同的
setter
和getter
方法。它可以帮助您使代码更具可读性,并立即解决这些类型的问题。我在帖子中举了一个例子,但这不一定是正确的例子,您必须根据应用程序逻辑找到实现它们的方法。