使用 MVC 和 DAO 模式在 JSP 页面的 HTML 中显示 JDBC ResultSet [英] Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

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

问题描述

我正在使用 JSP 和 JDBC 实现 MVC.我已经将一个数据库类文件导入到我的 JSP 文件中,我想显示一个 DB 表的数据.我不知道我应该如何将 Java 类中的 ResultSet 返回到 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.

p>

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

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<Product>.

  • 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);
            }
        }
    
    }
    

  • 最后是 /WEB-INF/products.jsp 中的 JSP 文件它使用 JSTL <c:forEach> 来迭代 List<Product>${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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆