gpt4 book ai didi

java - 如何正确返回一个根据用户 ID 显示数据的数组列表?

转载 作者:行者123 更新时间:2023-11-29 09:48:14 27 4
gpt4 key购买 nike

我已经能够正确显示一个数组列表,该数组列表显示我的 MySQL 数据库中的所有数据,但是我在如何根据用户 ID 显示数据时遇到了麻烦。

这是我的代码:

CreditsServlet.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 中。
  • 它最终会重定向到新的结果页面,该页面将显示制作人员名单。

关于java - 如何正确返回一个根据用户 ID 显示数据的数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55282924/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com