Issue
I'm trying to get data from the last 5 days from mysql database using servlet and jsp. I created a database class where it looks for the date between the last 5 days until the current date. Then on my serlvet, I called that method and store the values in a list and forward it the jsp page. I created a table in the jsp page to display the database data, but nothing is showing up. I debugged it and it was showing the list was empty. I am not sure what I am doing wrong. Here is my code:
Database method:
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 page:
<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>
Solution
The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.
If you want to get date within a range, you can choose the column type as 'data', 'datetime' etc. in database.
Answered By - Gurkan Yesilyurt