JSp

在JSP中显示数据库结果

发布于 2021-02-01 16:20:25

我有一个控制器servlet,它将请求转发到模型servlet。现在,当模型从数据库中获取结果时,我会将其转发到jsp。我不确定要在jsp中写什么,因为它需要显示一个表customerList.here是我的模型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;
    }
关注者
0
被浏览
100
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    使用JSTL
    c:forEach标签。如果您的servlet容器不支持它(例如Tomcat),则需要将jstl-1.2.jar放入/WEB- INF/lib。然后根据其文档在JSP页面顶部声明JSTL核心taglib

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

    然后,您可以在JSP中使用任何JSTL核心标记。您已在请求范围中使用属性名称放置了一个Vector<Customer>(eek,一个遗留类..而不是使用List<Customer> customers = new ArrayList<Customer>()customerList。因此可以${customerList}在EL中使用。将其提供给的items属性<c:forEach>并相应渲染<table>

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

    <c:out>如果涉及用户控制的输入,因为它可以防止XSS攻击是顺便说没有必要,而且很有用。

    也就是说,您的JDBC部分可以做得更好。如果发生异常,它对资源泄漏仍然很敏感。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看