gpt4 book ai didi

mysql - 将servlet的变量结果显示到jsp arraylist

转载 作者:行者123 更新时间:2023-11-29 10:56:18 25 4
gpt4 key购买 nike

我正在尝试通过servlet将我的数据从mysql显示到jsp中我面临的问题是我不确定数据是否正在传递,我收到 NullPointerException 错误。它甚至不显示从 mysql 获取的任何数据

我想做的是将我的 mysql id、名称、价格中的所有数据以格式表显示到 jsp 中

结果.jsp

<%                           
ArrayList<ProductBean> list=(ArrayList<ProductBean>)request.getAttribute("list");
for (int i = 0; i < list.size(); i++) {
list.get(i).getItemID();
list.get(i).getName();
list.get(i).getPrice();
}
%>

产品.java

  connection = DriverManager.getConnection(connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT id,name,price FROM item";

ArrayList < ProductBean > list = new ArrayList < ProductBean > ();

resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String itemID = resultSet.getString("id"); //fetch the values present in database
String name = resultSet.getString("name");
String price = resultSet.getString("price");
list.add(new ProductBean(itemID, name, price));

}
request.setAttribute("list", list);
request.getRequestDispatcher("/result.jsp").forward(request, response);

ProductBean.java

public class ProductBean {

private String itemID;
private String name;
private String price;

public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}

public ProductBean(){
}

public ProductBean(String itemID, String name, String price){
this.itemID = itemID;
this.name = name;
this.price = price;
}
}

最佳答案

如果没有获得 NULL 指针异常,请使用 out.println() 显示

<%                           
ArrayList<ProductBean> list=(ArrayList<ProductBean>)request.getAttribute("list");
for (int i = 0; i < list.size(); i++) {
out.println(list.get(i).getItemID());
out.println(list.get(i).getName());
out.println(list.get(i).getPrice());
}
%>

使用也可以使用JSTL

<c:forEach var="i" items=${list}>
<c:out value="${i.itemID}"/>
<c:out value="${i.name}"/>
<c:out value="${i.price}"/>

</c:forEach>

关于mysql - 将servlet的变量结果显示到jsp arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965831/

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