1

so I have a Servlet that retrieves some data from the database. For each row of this data I created an object and added all objects to an ArrayList of that object.

Now, I need the Servlet to pass the ArrayList back to the caller JSP, and print each attribute from each object in the ArrayList.

Do you guys would suggest the best way to do this? They way I am doing it obviously isn't working.

This is my JSP:

<%-- 
    Document   : ChartData
    Created on : Feb 11, 2014, 11:44:09 PM
    Author     : fabiolanza
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>

        <script>
            function myFunction() {

                var request = new XMLHttpRequest();
                request.open("GET", "http://localhost:8080/Test/Servlet2", true);
                request.onreadystatechange = function() {
                    if (request.readyState === 4) {

                        <%
                        java.util.ArrayList<objects.Data> DataArray = (java.util.ArrayList<objects.Data>) request.getAttribute("DataArray");

                        for(objects.Data d: DataArray){
                            out.print(d.type);
                            out.print(d.value);
                            out.print(d.month);
                        }
                        %>
                    }
                };

                request.send(null);

            }
        </script>

        <button onclick="myFunction()">Try it</button>


        <br><a href="/Test/index.html">Home</a>

    </body>
</html>

This is my Servlet: package servlet;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.ArrayList;

/**
 *
 * @author fabiolanza
 */

public class Servlet2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ArrayList<objects.Data> DataArray = new ArrayList<objects.Data>();

        request.setAttribute("DataArray", DataArray);

        // JDBC driver name and database URL
        String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        String DB_URL = "jdbc:mysql://localhost:3306/Tests";

        //  Database credentials
        String USER = "fabio";
        String PASS = "hacking";

        Connection conn = null;
        Statement stmt = null;

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();



        try {
            // Register JDBC driver
            Class.forName(JDBC_DRIVER);

            // Open a connection
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Execute SQL query
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM data";
            ResultSet rs = stmt.executeQuery(sql);


            out.println("<html><body>");
            // Extract data from result set
            while (rs.next()) {
                objects.Data d = new objects.Data(rs.getString("Type"), rs.getInt("Value"), rs.getString("Month"));

                DataArray.add(d);
            }
            String link = "/Test/Database.html";
            out.println("<a href="+link+">Database</a>");
            out.println("</body></html>");

//            request.getRequestDispatcher("ChartData.jsp").forward(request, response);

            // Clean-up environment
            out.close();
            rs.close();
            stmt.close();
            conn.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

Thanks!

user1060551
  • 421
  • 2
  • 11
  • 20

1 Answers1

0
  • By the way you are not Setting Any Attrubute (request.setAttribute("<somename>",DataArray)) after getting table datas and not forwarding to correspoting page from servlet [

    RequestDispatcher view=request.getRequestDispatcher("ChartData.jsp") view.forward(request, response)

].

  • you did this stuf by Ajax method in jsp page. (sorry to say, i don't know if it is possible and i didn't saw any jsp pgmr do it this way yet)

    function myFunction() {
       ------
        ---- 
          -----
            if (request.readyState === 4) { // ?--- what is meant by '===' (or) you mean '==' instead 
             -----
               ----
    }
    

Any way..

Two ways u could do this: 1. Using jstl 2. Using scriptlet in jsp (which is depreciated or not a standard nowadays)

-Using Jstl (query more about Jstl in Google if Don't get below mentioned code)

 1.  In servlet
       request.setAttribute("dataArray",DataArray); // set array list 
        RequestDispatcher view=request.getRequestDispatcher("ChartData.jsp""); 
        view.forward(request, response);
 2.  In Jsp page
           <c:forEach items="${dataArray}" var="item">
            <tr>
                <td><c:out value="${item.type}" /></td>  // 
                       ----
                         ---                          
        </c:forEach>              
  • Using Scriptlet in jsp (Again am Saying it is not a Standard or doing so is Depreciated. Refer this link why JSTL, by BalusC (stackoverflow)):

    • in jsp page:

    1 <% Query database as u mentioned in Servlet page after that Below mention code is from ur servlet page just apply it to ur Jsp page as shown:

     while (rs.next()) { %>
          <tr>
             <td> <%= rs.getString("Type") %> </td> (or)  u could do column number of needed 'field' in u database ie: if "Type" is at 3rd column <%= rs.getString(3)  ) 
             <br> <td> <%= rs.getString("Value") %> </td>
             <br>  <td> <%= rs.getString("Month") %> </td>              
        %< } %>
    

    2 and just run ur jsp in ur Jsp page in server. its done.

    Hope this helps you man.

Community
  • 1
  • 1
akcHitman
  • 117
  • 3
  • 16