我已经能够正确显示一个显示我的MySQL数据库中所有数据的arraylist,但是我在如何基于用户ID显示数据方面遇到了麻烦。
这是我的代码:
credits Servlet.Java
private void listTrans(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
int id = Integer.parseInt(request.getParameter("id"));
List<Credits> creditlist = OrganizerDao.getAllCredits(id);
for (Credits credits : creditlist) {
if (credits.getOrganizerid() == id) {
request.setAttribute("creditlist", creditlist);
}
request.getRequestDispatcher("credits.jsp").include(request, response);
}
}
任何帮助或方向将不胜感激。提前致谢
编辑:CreditsDao.java
public static List<Credits> getAllCredits(int id) throws SQLException {
List<Credits> creditlist=new ArrayList<>();
try{
Connection con= OrganizerDao.getConnection();
PreparedStatement ps=con.prepareStatement("select users.id AS organizerid, credits.invoiceid, " +
"credits.amountin AS creditamount, attendees.name AS payee, credits.purpose, gateway.name AS gatewayname " +
"from users, credits, attendees, gateway where credits.userid=users.id and credits.attendeeid=attendees.id " +
"and credits.gateway=gateway.id");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Credits credits = new Credits();
credits.setOrganizerid(rs.getInt("organizerid"));
credits.setInvoiceid(rs.getInt("invoiceid"));
credits.setCreditamount(rs.getDouble("creditamount"));
credits.setPayee(rs.getString("payee"));
credits.setPurpose(rs.getString("purpose"));
credits.setGatewayname(rs.getString("gatewayname"));
creditlist.add(credits);
}
con.close();
}catch(Exception e){e.printStackTrace();}
return creditlist;
}
比你想象的简单:
首先,修复DAO并使用参数。更改如下:
public static List<Credits> getAllCredits(int id) throws SQLException {
...
PreparedStatement ps=con.prepareStatement("select users.id AS organizerid, credits.invoiceid, " +
"credits.amountin AS creditamount, attendees.name AS payee, credits.purpose, gateway.name AS gatewayname " +
"from users, credits, attendees, gateway where credits.userid=users.id and credits.attendeeid=attendees.id " +
"and credits.gateway=gateway.id" +
" and users.id = ?"); // Added this extra SQL code
ps.setInt(1, id); // Added this code to use the id parameter
...
}
然后你可以简单地在servlet中使用结果列表:
private void listTrans(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
int id = Integer.parseInt(request.getParameter("id"));
List<Credits> creditlist = OrganizerDao.getAllCredits(id);
request.setAttribute("creditlist", creditlist);
response.sendRedirect("resultpage.jsp");
}
这段代码:
id
(过滤条件)。creditlist
中。