这侵犯了Law of Demeter
权利?见${book.author.name}
及${book.category.name}
下文。可以在带有表达式语言的 JSP 中执行此操作吗?
<c:set var="book" value="${book}" />
<table>
<tr>
<td>Title:</td><td><c:out value="${book.title}" /></td>
</tr>
<tr>
<td><c:out value="${book.description}" /></td>
</tr>
<tr>
<td>Price: </td><td><c:out value="${book.price}" /></td>
</tr>
<tr>
<td>Author: </td><td><c:out value="${book.author.name}" /></td>
</tr>
<tr>
<td>Category: </td><td><c:out value="${book.category.name}" /></td>
</tr>
</table>
</body>
</html>
${book}
属性是一个Book
对象。BookServlet
:
String id = request.getParameter("id");
BookService bookService = new BookService();
Book book = bookService.getBookById(Integer.valueOf(id));
request.setAttribute("book", book);
findBookById()
从BookService -> BookDao
public Book findBookById(int id) throws DaoException {
Book book = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = this.getConnection();
ps = con.prepareStatement(FIND_BOOK_BY_ID);
ps.setInt(1, id);
//Using a PreparedStatement to execute SQL...
rs = ps.executeQuery();
while (rs.next()) {
int bookId = rs.getInt("book_id");
String title = rs.getString("title");
String desc = rs.getString("description");
int authorId = rs.getInt("author_id");
String authorName = rs.getString("author_name");
int categoryId = rs.getInt("category_id");
String categoryName = rs.getString("book_category_name");
double price = rs.getDouble("price");
book = new Book(bookId);
book.setTitle(title);
book.setDescription(desc);
book.setPrice(price);
Author author = new Author(authorId);
author.setName(authorName);
book.setAuthor(author);
Category category = new Category(categoryId);
category.setName(categoryName);
book.setCategory(category);
}
} catch (SQLException e) {
throw new DaoException("findBookById() " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
throw new DaoException(e.getMessage());
}
}
return book;
}