title: How return array of items using json object in servlet and how to display using jquery
body: <p>I need to pass some items from my database to the web page. For this i used json object to pass the items from servlet to the jquery. But where i getting the problem is, </p>
  
  <ul>
  <li>If the database contains more element</li>
  <li>Then I obviously need to use the <code>ArrayList</code>.</li>
  <li>When I use <code>ArrayList</code> I don't know to pass the elements through <code>JSON</code>.</li>
  </ul>
  
  <p>My code is:</p>
  
  <pre><code>    PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      response.setHeader("Cache-control", "no-cache, no-store");
      response.setHeader("Pragma", "no-cache");
      response.setHeader("Expires", "-1");
  
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "GET");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      response.setHeader("Access-Control-Max-Age", "86400");
  
      Gson gson = new Gson();
      JsonObject myObj = new JsonObject();
  
      ArrayList&lt;Commenter&gt; commentInfo;
      try {
          commentInfo = commenting(uname,message,itemId,albumId);
          JsonElement commentObj = gson.toJsonTree(commentInfo);
          boolean nonNullElemExist= true;
          for (Commenter s: commentInfo) {
              if (s == null) {
                  nonNullElemExist = false;
                  break;
              }
          }
      if(nonNullElemExist == false){
          myObj.addProperty("success", false);
      }
      else {
          myObj.addProperty("success", true);
      }
      myObj.add("commentInfo", commentObj);
      out.println(myObj.toString());                   // I think problem is in this statement
  
      out.close();
      } catch (ClassNotFoundException | SQLException e) {
          System.out.println( "Error --&gt; " + displayErrorForWeb(e));
      }
  </code></pre>
  
  <p>And the method is:</p>
  
  <pre><code>   private ArrayList&lt;Commenter&gt; commenting(String uname,String message,int itemId,int albumId) throws ClassNotFoundException, SQLException {
     ArrayList&lt;Commenter&gt; commentList = new ArrayList&lt;Commenter&gt;();
     Connection conn = null; 
     conn=prepareConnection();
     PreparedStatement stmt = null;    
     String sql = null;
  
      try {     
          StringBuilder sb1=new StringBuilder(1024);
          sb1.append("insert into ").append(uname.trim()).append("comments values(?,?,?)");
          String sql1=sb1.toString();
          PreparedStatement stmt1 = conn.prepareStatement(sql1);
          stmt1.setString(1,uname);
          stmt1.setString(2,message);
          stmt1.setInt(3,itemId);
  
          StringBuilder sb=new StringBuilder(1024);
          sb.append("select * from ").append(uname.trim()).append("comments");
          sql=sb.toString();
          stmt = conn.prepareStatement(sql);
         ResultSet rs = stmt.executeQuery();
  
          while(rs.next()){
              Commenter comment = new Commenter();
              comment.setUname(rs.getString("uname").trim());
              comment.setComment(rs.getString("comment").trim());
              commentList.add(comment);
             }                                                                        
  
          rs.close();                                                              
          stmt.close();                                                            
          stmt = null;                                                             
  
  
          conn.close();                                                            
          conn = null;                                                  
  
      }                                                              
      catch(Exception e){System.out.println( "Error --&gt; " + displayErrorForWeb(e));}                     
  
      finally {                                                      
  
          if (stmt != null) {                                           
              try {                                                        
                  stmt.close();                                               
              } catch (SQLException sqlex) {                               
                  System.out.println( "Error --&gt; " + displayErrorForWeb(sqlex));         
              }                                                            
  
              stmt = null;                                           
          }                                                       
  
          if (conn != null) {                                     
              try {                                                  
                  conn.close();                                         
              } catch (SQLException sqlex) {                         
                  System.out.println( "Error --&gt; " + displayErrorForWeb(sqlex));
              }                                                      
  
              conn = null;                                           
          }                                                       
      }             
  
      return commentList;
  
  } 
  </code></pre>
  
  <p>And the jquery is :</p>
  
  <pre><code>  $.ajax({
         type: "GET",
          url: "Comments",
          data:'comm='+encodeURIComponent(comm)+'&amp;'+'data-id='+encodeURIComponent(dataid)+'&amp;'+'data-alid='+encodeURIComponent(dataalid),
          dataType: "json",
          success: function( data, textStatus, jqXHR) 
          {
              if(data.success)
              {
         /*   $.each(data, function(i, item)
                       {*/
  
                      var newcommhtml = '&lt;div id="c0'+thecid+'" class="cnew clearfix"&gt; &lt;section class="c-author"&gt;';
                      newcommhtml = newcommhtml + '&lt;h3&gt;Anonymous&lt;/h3&gt;';
                      newcommhtml = newcommhtml + '&lt;span class="pubdate"&gt;'+month+' '+day+', '+year+'&lt;/span&gt; &lt;/section&gt;';
                      newcommhtml = newcommhtml + '&lt;section class="c-content"&gt;';
                      newcommhtml = newcommhtml + '&lt;img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava"&gt;';
                      newcommhtml = newcommhtml + '&lt;p&gt;'+nl2br(data.commentInfo.comment)+'   '+nl2br(data.commentInfo.itemId)+'&lt;/p&gt; &lt;/section&gt;&lt;/div&gt;';
                      /*newcommhtml = newcommhtml + '&lt;p&gt;'+nl2br(item.commentInfo.comment)+'   '+nl2br(item.commentInfo.itemId)+'&lt;/p&gt; &lt;/section&gt;&lt;/div&gt;';
                      });
                      */                  
                      var thelm = "#c0"+thecid;
                      commwrap.append(newcommhtml);
                      $(thelm).hide().fadeIn('slow');
  
                      setTimeout(function() { $(thelm).addClass('green'); }, 800);
  
                      $("#comm").val("");
                      thecid++;
  
                      if(errorspan.html() != null) {
                          errorspan.remove();
                      }
              }
  
            },
       error: function(jqXHR, textStatus, errorThrown)
        {
           alert("error"+errorThrown);
           console.log("Something really bad happened " + textStatus);
        },
  });
  </code></pre>
  
  <p>If I use <code>$each()</code> <code>success</code> block wasn't work at all.</p>
  
  <p>Please any one tell me how to do the stuff for this case.........thanks.......</p>