Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern(使用 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 - Productclass 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
- 如何避免JSP文件中出现Java代码?
- Servlet 中的 doGet 和 doPost
- 我应该如何在基于 servlet 的应用程序中连接到 JDBC 数据库/数据源?
- 设计模式基于网络的应用程序
- RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
- 如何将列数未知的 ResultSet 映射到 List 并在 HTML 表格中显示?
- 如何通过单击 JSP 页面中的超链接或按钮将当前项传递给 Java 方法?
这篇关于使用 MVC 和 DAO 模式在 JSP 页面的 HTML 中显示 JDBC ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 MVC 和 DAO 模式在 JSP 页面的 HTML 中显示 JDBC ResultSet
 
				
         
 
            
        基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				