0

I am working on a project which involves retrieving data from a MySQL database and paginating it. I am using JSON AJAX and JavaScript. I am new to JSON and AJAX. I have obtained the data from the DB and stored in the JSON object using a servlet. My question is, how do I pass this data from my Servlet to the target HTML file ? If I would use Javascript, then how ?

Servlet File

import java.io.IOException;
import java.sql.*;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.*;

public class DbServlet extends HttpServlet implements DatabaseConstants {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) {
        String jdbcDriver, jdbcURL, username, password, query;
        String errorCode = null;
        int i = 0;
        int columnCount = 0;

        response.setContentType("application/json");

        jdbcDriver = request.getParameter(JDBC_DRIVER);
        jdbcURL = request.getParameter(JDBC_URL);
        username = request.getParameter(USERNAME);
        password = request.getParameter(PASSWORD);
        query = request.getParameter(QUERY);

        Connection con = null;
        PrintWriter out = null;
        Statement stmt = null;
        ResultSet resultSet = null;

        JSONObject jsonObject = null, sendDBJsonObject = null;
        JSONArray dbResultJSON;

        try {
            out = response.getWriter();

            Class.forName(jdbcDriver);
            System.out.println("Attempting to establish connection..");
            con = DriverManager.getConnection(jdbcURL, username, password);
            System.out.println("Connection succeeded..");

            stmt = con.createStatement();
            resultSet = stmt.executeQuery(query);

            if (!resultSet.first()) {
                out.println("<h3>There are no rows in the requested database.</h3>");
            } else {

                ResultSetMetaData rsmd = resultSet.getMetaData();

                columnCount = rsmd.getColumnCount();

                dbResultJSON = new JSONArray();

                resultSet.beforeFirst();
                while (resultSet.next()) {
                    // out.println("<tr>");
                    jsonObject = new JSONObject();
                    for (i = 1; i <= columnCount; i++) {
                        jsonObject.put(rsmd.getColumnLabel(i),
                                (resultSet.getString(i) == null ? "empty"
                                        : resultSet.getString(i)));
                    }
                    dbResultJSON.add(jsonObject);
                }
                sendDBJsonObject = new JSONObject();
                sendDBJsonObject.put("dbResults", dbResultJSON);
                /*
                 * out.println("</table>"); out.println("<select>" +
                 * "<option value=\"five\">5</option>" +
                 * "<option value=\"ten\">10</option>" +
                 * "<option value=\"twenty\">20</option>" +
                 * "<option value=\"fifty\">50</option>" + "</select>");
                 */
                response.sendRedirect("result.html");
            }
        } catch (SQLException | ClassNotFoundException e) {

            if (jdbcDriver.isEmpty())
                errorCode = "SQL Error. Please enter a valid SQL Driver.";
            else if (jdbcURL.isEmpty())
                errorCode = "SQL Error. Please enter a valid SQL URL.";
            else if (username.isEmpty())
                errorCode = "Access Denied. Please enter a valid Username.";
            else if (password.isEmpty())
                errorCode = "Access Denied. Please enter a valid password.";
            else if (query.isEmpty())
                errorCode = "SQL Error. Cannot issue empty query.";
            else
                errorCode = e.getLocalizedMessage();

            try {
                response.sendError(500, errorCode);
            } catch (IOException ioE) {
                ioE.printStackTrace();
            }

        } catch (IOException ioE) {
            ioE.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null)
                try {
                    stmt.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            if (out != null)
                out.close();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}
formidableXenon
  • 55
  • 2
  • 15

1 Answers1

1

If i am correct, i would be doing the changes as below (at least i have done for my code):

JSONObject job=new JSONObject(); //create a JSON Object obj.
JSONArray jArray = new JSONArray(); //create a JSON Array obj.

PreparedStatement ps=conn.prepareStatement(sql);

ResultSet rs=ps.executeQuery();

while(rs.next()){

        /*assign the resultset with a variable into the JSON Obj */
        job.put("rs_val_one", rs.getString(1));
        job.put("rs_val_two", rs.getString(2));

        jArray.put(job); //add the JSON obj (job) to an JSON array.This will make it easier to fetch the results of each.

        job.clear(); //clear the obj. from the memory

}

Well you have done most of the part correct, it seems. Only difference in the above part i have assigned the JSONObject object into a JSON array.

Now Second, in the response section, instead of sending a redirect response directly to the HTML/JSP page, you would need to bind the JSONArray obj. data to the response. So instead of

response.sendRedirect("result.html");

do this:

response.getWriter().write(jArray.toString());

This takes care of the Servlet section. Now in your result.html page, you would need to add the below code inorder to fetch the jArray data.

/** Calling the servlet using Jquery getJSON method 
  * @url: Servlet URL 
  * @data: the value servlet returns
*/
$.getJSON(url, function(data) {

      //iterating over each value that the servlet returns
      $.each(data, function(key, value) {
               Alert(value.rs_val_one); //alerting the values set in the JSONObject of the Sevlet.
               Alert(value.rs_val_two);
     });
});

Note here i have called the Servlet from the Same page using JQuery AJAX. The above code calls the servlet and alerts the data that the jsonarray returns.

For more detailed explaination, you may try this link as mentioned in the comment above.

Hope this solves your query :)

Community
  • 1
  • 1
Rishu Shrivastava
  • 3,745
  • 1
  • 20
  • 41