我有一个无状态的 Session Bean,我在其中从数据库中获取值并将它们写在 Arraylist 中,然后返回给 servlet。在一个 servlet 中,我在 JSP 页面上发送 ArrayList 并尝试显示该值,但只显示“dataList”行,我的错误是什么?
这是我的代码:
ViewBean.java
//imports
@Stateless
@LocalBean
public class ViewBean {
public List getData() {
ResultSet rs = null;
List list = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c_store", "root", "root");
Statement stmt = con.createStatement();
String query = "SELECT product.name_prod, product.price_prod, buy.number_buy, client.name_client, client.date_client FROM product, buy, client WHERE product.id_prod = buy.id_buy = client.id_client;";
stmt.executeQuery(query);
rs = stmt.getResultSet();
list = new ArrayList();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getInt(2));
list.add(rs.getInt(3));
list.add(rs.getString(4));
list.add(rs.getString(5));
}
rs.close();
stmt.close();
con.close();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
ViewServlet.java
//imports
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
ViewBean viewBean;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
List data = new ArrayList();
data = viewBean.getData();
request.setAttribute("dataList", data);
for(int i = 0; i<data.size(); i++){
out.println(data.get(i));
}
}
}
视图.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Records</title>
</head>
<body>
<c:forEach var="item" items="dataList">
<b><c:out value="${item}" /></b>
</c:forEach>
</body>
</html>