Search code examples
jspservletsarraylistgetattribute

Display a Class ArrayList on JSP page


I am a beginner to Java.

What I am trying to achieve is take an input of Product code from JSP (index.jsp) webpage, call a servlet (getDetails) and get description and balance on hand for multiple location, from a DB2-I-series sedrver

In Servlet for description I am using Map, but to get balance of multiple location i am using a custom class ArrayList (displayOnHand).

Data is getting properly captured in servlet page for balance at multiple location, but when I do a setAttribute in Servlet and getAttribute in JSP for the same, I am not able extract data as 1 field at a time.

Can someone please help men.

Following is my code

-------- 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;
}
}

Solution

  • you can add instance of Product in the list e.g. List<Product> productList = new ArrayList<Product>(); and add the product as productList.add(p); where p is any instance of Product. For display use for loop e.g.

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