在 JSP 页面上显示 Class ArrayList

Display a Class ArrayList on JSP page

我是 Java 的初学者。

我想要实现的是从 JSP (index.jsp) 网页输入产品代码,调用 servlet (getDetails) 并获取多个位置的描述和手头余额,来自 DB2-I 系列 sedrver

在 Servlet 中,我使用 Map 进行描述,但为了平衡多个位置,我使用自定义 class ArrayList (displayOnHand)。

数据在 servlet 页面中被正确捕获以在多个位置保持平衡,但是当我在 Servlet 中执行 setAttribute 并在 JSP 中执行相同的 getAttribute 时,我无法将数据提取为 1 个字段时间.

有人可以帮助男人吗。

以下是我的代码

-------- getDetails Servlet ------------------


public class getDetails extends HttpServlet {

  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
   * methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
      /* TODO output your page here. You may use following sample code. */
      /* write your code here */

      Map < String, String > messages = new HashMap < String, String > ();
      ArrayList columnNames = new ArrayList();
      displayOnHand data = new displayOnHand();
      ArrayList < displayOnHand > dataList = new ArrayList < displayOnHand > ();

      String scanSKU = request.getParameter("SKUScan");
      if (scanSKU == null || scanSKU.trim().isEmpty()) {
        messages.put("scanSKU", "Please Enter SKU/UPC/EAN Code");
      }

      if (messages.isEmpty()) {

        String driver = getServletContext().getInitParameter("driver");
        String connectionString = getServletContext().getInitParameter("connectionString");
        String username = getServletContext().getInitParameter("username");
        String password = getServletContext().getInitParameter("password");

        try {
          Class.forName(driver);
          Connection conn = DriverManager.getConnection(connectionString, username, password);
          Statement stmt = conn.createStatement();
          String rsstmt = "select IDESCR from mm510lib.invmst where inumbr =" + scanSKU;
          ResultSet rs = stmt.executeQuery(rsstmt);

          String SKUName = "";
          while (rs.next()) {
            SKUName = rs.getString(1);
          }
          //String SKUName = rs.getString(1);
          messages.put("SKUDescription", SKUName);
          stmt = conn.createStatement();
          rsstmt = "select istore, IBHAND from mm510lib.invbal where inumbr =" + scanSKU;
          rs = stmt.executeQuery(rsstmt);

          ResultSetMetaData md = rs.getMetaData();
          int columns = md.getColumnCount();

          //  Get column names
          //for (int i = 1; i <= columns; i++) {
          //    columnNames.add(md.getColumnName(i));
          // }
          //  Get row data
          //while (rs.next()) {
          //    ArrayList row = new ArrayList(columns);
          //    for (int i = 1; i <= columns; i++) {
          //        row.add(rs.getObject(i));
          //    }
          //    data.add(row);
          //}
          while (rs.next()) {
            //displayOnHand data = new displayOnHand();
            data.setLocationCode(rs.getInt(1));
            data.setOnhand(rs.getInt(2));
            dataList.add(data);
          }
          rs.close();
          stmt.close();
          conn.close();
        } catch (ClassNotFoundException | SQLException ex) {
          Logger.getLogger(getDetails.class.getName()).log(Level.SEVERE, null, ex);
          messages.put("connection", "Connection to Database could not be established");
        }

        request.setAttribute("messages", messages);
        request.setAttribute("onHandClass", data);
        request.setAttribute("OnHandDetails", dataList);
        request.getRequestDispatcher("index.jsp").forward(request, response);
      }
    }
  }


---------------------------------------------------- index.jsp ----------------------------------------------------


<%@page import="java.util.List" %>
  <%@page import="java.sql.Array" %>
    <%@page import="java.util.Locale.Category" %>
      <%@page import="java.util.ArrayList" %>
        <%@page import="JavaPackages.*" %>
          <%@page contentType="text/html" pageEncoding="UTF-8" %>
            <!DOCTYPE html>
            <html>

            <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>Store MIS V0.1</title>
              <link href="css/index.css" rel="stylesheet" type="text/css" />

              <script type='text/javascript'>
                function isNumber(evt) {
                  evt = (evt) ? evt : window.event; // for IE
                  var charCode = (evt.which) ? evt.which : evt.keyCode;
                  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                    return false;
                  }
                  return true;
                }
              </script>
            </head>

            <body>
              <div class="hypLogo">
                <img src="images/logo.jpg" alt="" />
              </div>
              <div class="container">
                <div class="pageHeader">
                  <h1>Store MIS</h1>
                  <form action="getDetails.do" method="POST">
                    <p>
                      <input type="text" name="SKUScan" value="" placeholder="Scan SKU" onkeypress="return isNumber(event)" />
                    </p>

                    <span class="error">${messages.scanSKU}</span>
                    <p class="submit">
                      <input type="submit" name="commit" value="Enter">
                    </p>
                    <span class="error">${messages.connection}</span>
                    <span class="error">${messages.SKUDescription}</span>
                  </form>
                </div>
              </div>
              <% out.println( "in Script"); if (request.getAttribute( "OnHandDetails") !=n ull) { // retrieve your list from the request, with casting ArrayList<displayOnHand>list = (ArrayList
                <displayOnHand>) request.getAttribute("OnHandDetails"); displayOnHand tempData = new displayOnHand() ; out.println("Array Size" + list.size()); // print the information about every category of the list for (int i = 0; i
                  < list.size(); i++) { tempData.equals(list.get(i));
                  } } %>
            </body>

            </html>

------------- displayOnHand Class ---------------

public class displayOnHand {

private int storeNumber;
private int onHandBal;

public displayOnHand() {

}

public void setLocationCode(int strNum) {
    storeNumber = strNum;
}

public int getLocationCode() {
    return storeNumber;
}

public void setOnhand(int onHand) {
    onHandBal = onHand;
}

public int getOnHand() {
    return onHandBal;
}
}

您可以使用jstl 标签库来遍历arraylist。例如,您可以使用 c:forEach 标签。

for迭代你也可以使用for循环 例如

for(i=0;i<list.size();i++)
out.println(list.get(i));

您也可以像@vivek 提到的那样使用 JSTL 标签

你真的应该尝试使用 JSTL。

它就像(从 JSTL c:forEach printing ${} 偷来的)一样简单:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title></title>
</head>
<body>

Hello from products page.<br/>

<c:forEach var="prod" items="${products}">
    ${prod.price}
    ${prod.id}
</c:forEach>


</body>
</html>

有一个不错的 XML 文件。

如果你真的不会用JSTL,那就是:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.util.List"%>
<%@page import="package.to.Product"%>

<html>
<head>
    <title></title>
</head>
<body>

Hello from products page.<br/>
<%
    List<Product> products = (List<Product>) request.getAttribute("products");
    for (Product prod: products) {
        page.setAttribute("prod", prod);
%>
    ${prod.price}
    ${prod.id}
<% } %>

</body>
</html>

是不是很丑(而且我什至没有测试过)?相信我:除非你真的不能做不同的事 避免 scriptlets !

您可以在列表中添加产品实例,例如 List<Product> productList = new ArrayList<Product>(); 并将产品添加为 productList.add(p);,其中 p 是产品的任何实例。用于显示循环,例如

for(i=0;i<productList.size();i++) 
{ 
Product product = list.get(i); 
out.println(product.price); 
out.println(product.id);  
}