从数据库获取最新数据到jsp页面

时间:2017-01-06 23:48:52

标签: java mysql jsp servlets

我正在尝试使用servlet和jsp从mysql数据库获取过去5天的数据。我创建了一个数据库类,用于查找过去5天到当前日期之间的日期。然后在我的serlvet上,我调用了该方法并将值存储在列表中并将其转发到jsp页面。我在jsp页面中创建了一个表来显示数据库数据,但没有显示任何内容。我调试它,它显示列表是空的。我不确定我做错了什么。这是我的代码:

数据库方法:

public static List getMaxRecordsHomePage(int id) {
    List recordList = new ArrayList<>();

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    Date date = new Date();
    String currentDate = dateFormat.format(date);

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -5);
    Date previousDate = cal.getTime();
    String fromDate = dateFormat.format(previousDate);

    try {
        Connection conn = DBConnection.getConnection();
        String query = "SELECT * FROM record WHERE userId=? AND date BETWEEN ? AND ?";
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setInt(1, id);
        stmt.setString(2, fromDate);
        stmt.setString(3, currentDate);
        ResultSet rs = stmt.executeQuery();

        while(rs.next()) {
            Record records = new Record();
            records.setId(id);
            records.setCategory(rs.getString("category"));
            records.setDescription(rs.getString("description"));
            records.setAmount(rs.getString("amount"));
            records.setDate(rs.getString("date"));
            recordList.add(records);
        }   
    } catch (Exception e) {
        System.out.println(e);
    }
    return recordList;
    }
}

Serlvet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
{
    int id = SessionService.getSessionId(request, response);                    
    List recordList = FinanceService.getMaxRecordsHomePage(id);
    request.setAttribute("recordList", recordList);

    RouteService.routeDispatcher(request, response, "homepage.jsp");
}

JSP页面:

<table>
    <caption>Recent Records</caption>
    <tr>
        <td>Category</td>
        <td>Short Description</td>
        <td>Amount</td>
        <td>Date</td>
    </tr>
    <c:forEach var="Records" items="${recordList}">
        <tr>
            <td><c:out value="${Records.category}"/></td>
            <td><c:out value="${Records.description}"/></td>
            <td>$<c:out value="${Records.amount}"/></td>
            <td><c:out value="${Records.date}"/></td>
        </tr>
    </c:forEach>
</table>

1 个答案:

答案 0 :(得分:1)

  

BETWEEN运算符选择范围内的值。值可以是数字,文本或日期。

如果您想在一个范围内获取日期,您可以在数据库中选择列类型为“数据”,“日期时间”等。