使用MVC和DAO模式在JSP页面的HTML中显示JDBC ResultSet?
设计良好的MVC方法中,JSP文件不应包含任何Java代码行,而Servlet类不应包含任何JDBC代码行。
假设要在网上商店中显示产品列表,则需要创建以下代码。
一个Product代表产品的真实世界的实体类,它应该只是一个Javabean的。
public class Product { private Long id; private String name; private String description; private BigDecimal price; // Add/generate getters/setters/c'tors/equals/hashcode boilerplate. }
一个DAO类,它完成所有讨厌的JDBC工作并返回一个 List<Product>。
List<Product>
public class ProductDAO { private DataSource dataSource; public ProductDAO(DataSource dataSource) { this.dataSource = dataSource; } public List<Product> list() throws SQLException { List<Product> products = new ArrayList<Product>(); try ( Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT id, name, description, price FROM product"); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { Product product = new Product(); product.setId(resultSet.getLong("id")); product.setName(resultSet.getString("name")); product.setDescription(resultSet.getString("description")); product.setPrice(resultSet.getBigDecimal("price")); products.add(product); } } return products; } }
一个Servlet类,它获取列表并将其放入请求范围。
@WebServlet("/products") public class ProductsServlet extends HttpServlet { @Resource(name="jdbc/YourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml. private DataSource dataSource; private ProductDAO productDAO; @Override public void init() { productDAO = new ProductDAO(dataSource); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<Product> products = productDAO.list(); request.setAttribute("products", products); // Will be available as ${products} in JSP request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); } catch (SQLException e) { throw new ServletException("Cannot obtain products from DB", e); } } }
最后,在JSP文件中/WEB-INF/products.jsp,使用JSTL <c:forEach>进行迭代,List<Product>在EL中使它可用${products},并使用JSTL <c:out>来转义字符串属性,以便避免在涉及用户控制的输入时出现XSS漏洞。
/WEB-INF/products.jsp
JSTL <c:forEach>
${products}
<c:out>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/format" prefix="fmt" %> ... <table> <c:forEach items="${products}" var="product"> <tr> <td>${product.id}</td> <td><c:out value="${product.name}" /></td> <td><c:out value="${product.description}" /></td> <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td> </tr> </c:forEach> </table>
要使其正常工作,只需通过其URL调用servlet。假设了一个Servlet注解@WebServlet("/products")或映射在web.xml与<url-pattern>/products</url-pattern>,那么你可以把它叫做http://example.com/contextname/products
@WebServlet("/products")
web.xml
<url-pattern>/products</url-pattern>
http://example.com/contextname/products