我试图通过servlet将我的数据从mysql显示到jsp中 我面临的问题是我不确定数据是否正在传递,我收到NullPointerException错误。它甚至不显示从mysql中获取的任何数据
我想要做的是将我的mysql id,name,price中的所有数据显示到格式表中的jsp中
result.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();
}
%>
product.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;
}
}
答案 0 :(得分:1)
如果没有获得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>