【问题标题】:Displaying database result in JSP在 JSP 中显示数据库结果
【发布时间】:2010-11-16 16:06:44
【问题描述】:

我有一个控制器 servlet,它将请求转发给模型 servlet。现在,当模型从数据库中获取结果时,我将其转发给 jsp。我不确定在 jsp 中写什么,因为它需要显示一个 customerList 表。这里是我的模型 servlet 的一部分:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{
    Connection connection = getDatabaseConnection();
    request.setAttribute("customerList", getCustomerList(connection));
    closeDatabaseConnection(connection);
}

private Vector<Customer> getCustomerList(Connection con)
{
    String sqlStr =
            "SELECT * " +
            "FROM Customer " +
            "ORDER BY Name";
    PreparedStatement stmt = null;
    ResultSet rs = null;
    Vector<Customer> customers = new Vector<Customer>();

    try
    {
        stmt = con.prepareStatement(sqlStr);
        rs = stmt.executeQuery();

        while (rs.next())
        {
            Customer customer = new Customer();
            customer.setId(rs.getInt("Id"));
            customer.setName(rs.getString("Name"));
            customer.setAddress(rs.getString("Address"));

            customers.add(customer);
        }

        rs.close();
        stmt.close();
    }
    catch (SQLException sqle)
    {
        sqle.printStackTrace();
    }
    finally
    {
        return customers;
    }

【问题讨论】:

    标签: jsp servlets


    【解决方案1】:

    使用JSTLc:forEach 标签。如果您的 servletcontainer 不支持它(例如 Tomcat),那么您需要在 /WEB-INF/lib 中删除 jstl-1.2.jar。然后根据其文档在 JSP 页面顶部声明 JSTL core taglib

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    

    然后您可以在 JSP 中使用任何 JSTL 核心标签。您已经在请求范围内放置了一个Vector&lt;Customer&gt;(eek,一个遗留类.. 而不是使用List&lt;Customer&gt; customers = new ArrayList&lt;Customer&gt;()),属性名称为customerList。所以它可以通过 EL 中的${customerList} 获得。将其提供给&lt;c:forEach&gt;items 属性并相应地渲染&lt;table&gt;

    <table>
        <c:forEach items="${customerList}" var="customer">
            <tr>
                <td><c:out value="${customer.id}" /></td>
                <td><c:out value="${customer.name}" /></td>
                <td><c:out value="${customer.address}" /></td>
            </tr>
        </c:forEach>
    </table>
                
    

    顺便说一句,&lt;c:out&gt; 不是必需的,但如果它涉及用户控制的输入,则很有用,因为它可以防止 XSS 攻击。

    也就是说,您的 JDBC 部分可以做得更好。在异常情况下它仍然对资源泄漏很敏感。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多