簡體   English   中英

顯示來自ArrayList的數據(EJB + Servlet + JSP(JSTL))

[英]Displaying data from ArrayList (EJB + Servlet + JSP(JSTL))

我有一個無狀態的Session Bean,從數據庫中獲取值並將它們寫到Arraylist中,然后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));
    }
}
   }

view.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>

您忘記將dataList聲明為變量,請在循環中items屬性:

<c:forEach var="item" items="${dataList}">
                             ^ here is the bug, add the dollar sign and the curly braces
    <b><c:out value="${item}" /></b>
</c:forEach>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM