首页 > 解决方案 > 通过 LinkedList 在 JSP 中打印名称而不是按顺序打印

问题描述

我正在尝试将排序顺序应用于 HTML 搜索表单,并按指定顺序打印结果。我一生都无法弄清楚为什么它不起作用,除非我不知道关于 LinkedLists 的一些东西。我对开发比较陌生,所以这是可能的。请记住,这是为我的编码训练营分配的任务,所以虽然我感谢所有建议,但我们被要求不要导入除提供的库之外的任何库,并且我们也被要求不要使用 servlet。下面的代码

这个块可以在我的 JDBC 中找到。

    public List<Customer> searchAndSortCustomers(String search, String sort) {
        List<Customer> customers = new LinkedList<>();

        String query = "SELECT first_name, last_name, email, activebool FROM customer WHERE first_name ILIKE ? OR last_name ILIKE ? ORDER BY ?";
        SqlRowSet result = jdbcTemplate.queryForRowSet(query, "%" + search + "%", "%" + search + "%", sort);

        while(result.next()) {
            customers.add(mapRowToCustomer(result));
        }

        return customers;
    }

辅助方法 mapRowToCustomer

private Customer mapRowToCustomer(SqlRowSet result) {
        Customer customer = new Customer();

        customer.setFirstName(result.getString("first_name"));
        customer.setLastName(result.getString("last_name"));
        customer.setEmail(result.getString("email"));
        customer.setActive(result.getBoolean("activebool"));

        return customer;
    }

带有表单等的 JSP 页面

<form method="GET" action="customerSearch">

    <label for="search">First or Last Name</label>
    <input name="search" type="text"/>

    <br>
    <br>

    <label for="sort">Sort By</label>
    <select name="sort">
        <option value="first_name">First Name</option>
        <option value="last_name">Last Name</option>
        <option value="activebool">Active</option>
    </select>

    <br>
    <br>

    <input type="submit"/>

</form>

<c:if test="${not empty param.search}">
    <table id="customer-flex">
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Active</th>
        </tr>
        <c:forEach var="customer" items="${customers}">
            <tr>
                <td>${customer.firstName} ${customer.lastName}</td>
                <td>${customer.email}</td>
                <td>${customer.active}</td>
            </tr>
        </c:forEach>
    </table>
</c:if>

该查询在带有复制/粘贴值的 dbvisualizer 中工作,只是为了仔细检查我没有为 db 列标题犯任何拼写错误。任何建议将不胜感激!

谢谢,

标签: javapostgresqljsp

解决方案


“您不能将要排序的列作为?参数传递给 ORDER BY 子句。– a_horse_with_no_name”

这是正确答案,再次感谢!


推荐阅读