将JSON数组从Java Servlet传递到HTML

时间:2014-08-05 05:34:08

标签: java javascript ajax json

我正在开发一个涉及从MySQL数据库中检索数据并对其进行分页的项目。我正在使用JSON AJAX和JavaScript。我是JSON和AJAX的新手。我从DB获取了数据并使用servlet存储在JSON对象中。我的问题是,如何将这些数据从我的Servlet传递到目标HTML文件? 如果我会使用Javascript,那怎么样?

Servlet文件

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

1 个答案:

答案 0 :(得分:1)

如果我是正确的,我会按照以下进行更改(至少我已为我的代码做了)

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

}

好吧,你似乎已经完成了大部分正确的部分。只有上面部分的差异我已将JSONObject对象分配到JSON数组中。

现在第二,在响应部分中,您需要绑定JSONArray对象,而不是直接向HTML / JSP页面发送重定向响应。数据到响应。而不是

response.sendRedirect("result.html");

这样做:

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

这会处理Servlet部分。现在在result.html页面中,您需要添加以下代码才能获取jArray数据。

/** 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);
     });
});

请注意,我使用JQuery AJAX从同一页面调用了Servlet。上面的代码调用servlet并警告jsonarray返回的数据。

如需更详细的解释,您可以尝试以上评论中提到的link

希望这能解决您的疑问:)