本文介绍了使用 MVC 和 DAO 模式在 JSP 页面中以 HTML 格式显示 JDBC ResultSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSP 和 JDBC 实现 MVC.我已经将一个数据库类文件导入到我的 JSP 文件中,我想显示一个 DB 表的数据.我不知道我应该如何将 ResultSet 从 Java 类返回到 JSP 页面并将其嵌入到 HTML 中.

I'm implementing MVC using JSP and JDBC. I have imported a database class file to my JSP file and I would like to show the data of a DB table. I don't know how I should return the ResultSet from the Java class to the JSP page and embed it in HTML.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

在设计良好的 MVC 方法中,JSP 文件不应包含任何 Java 代码行,servlet 类不应包含任何 JDBC 代码行.

In a well designed MVC approach, the JSP file should not contain any line of Java code and the servlet class should not contain any line of JDBC code.

>

假设您要在网上商店中显示产品列表,则需要创建以下代码.

Assuming that you want to show a list of products in a webshop, the following code needs to be created.

  • 一个 Product 类表示产品的真实世界实体,它应该只是一个 Javabean.

  • A Product class representing a real world entity of a product, it should be just a 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.

  • A DAO class which does all the nasty JDBC work and returns a nice 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 类,用于获取列表并将其放入请求范围.

  • A servlet class which obtains the list and puts it in the request scope.

    @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 迭代 List${products}EL 中提供,并使用 JSTL<c:out> 转义字符串属性,以避免在涉及用户时出现 XSS 漏洞 -受控输入.

  • Finally a JSP file in /WEB-INF/products.jsp which uses JSTL <c:forEach> to iterate over List<Product> which is made available in EL by ${products}, and uses JSTL <c:out> to escape string properties in order to avoid XSS holes when it concerns user-controlled input.

    <%@ 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

    To get it to work, just call the servlet by its URL. Provided that the servlet is annotated @WebServlet("/products") or mapped in web.xml with <url-pattern>/products</url-pattern>, then you can call it by http://example.com/contextname/products

    这篇关于使用 MVC 和 DAO 模式在 JSP 页面中以 HTML 格式显示 JDBC ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-20 18:25