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

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

问题描述

我正在使用JSP和JDBC实现MVC。我已将数据库类文件导入到我的JSP文件中,并且我想显示数据库表的数据。我不知道如何将 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.

如何实现这一目标?

推荐答案

在设计良好的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.


  • 一个产品类,代表一个真实世界的实体产品,它应该只是一个 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.
}


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


  • A 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> 进行迭代列表<产品> EL 提供 $ {products} ,并使用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>
    


  • 要让它发挥作用,只需致电servlet的URL。前提是servlet注释为 @WebServlet(/ products),或者使用<$ c映射到 web.xml $ c>< 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

    • How to avoid Java code in JSP files?
    • doGet and doPost in Servlets
    • How should I connect to JDBC database / datasource in a servlet based application?
    • Design Patterns web based applications
    • RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
    • How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?
    • How do I pass current item to Java method by clicking a hyperlink or button in JSP page?

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

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