显示ArrayList中的数据(EJB + Servlet + JSP(JSTL))

时间:2013-04-14 12:07:15

标签: java css jsp servlets ejb

我有一个无状态会话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));
    }
}
   }

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>

1 个答案:

答案 0 :(得分:0)

您忘了将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>