简体   繁体   English

将JSON数组从Java Servlet传递到HTML

[英]Passing JSON Array from Java Servlet to HTML

I am working on a project which involves retrieving data from a MySQL database and paginating it. 我正在从事一个涉及从MySQL数据库检索数据并对其进行分页的项目。 I am using JSON AJAX and JavaScript. 我正在使用JSON AJAX和JavaScript。 I am new to JSON and AJAX. 我是JSON和AJAX的新手。 I have obtained the data from the DB and stored in the JSON object using a servlet. 我已从数据库获取数据,并使用servlet将其存储在JSON对象中。 My question is, how do I pass this data from my Servlet to the target HTML file ? 我的问题是,如何将这些数据从Servlet传递到目标HTML文件? If I would use Javascript, then how ? 如果我要使用Javascript,那又如何?

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

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. 唯一不同的是,我已将JSONObject对象分配到JSON数组中。

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. 现在,第二,在“响应”部分中,您需要绑定JSONArray obj,而不是直接将重定向响应发送到HTML / JSP页面。 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. 这负责Servlet部分。 Now in your result.html page, you would need to add the below code inorder to fetch the jArray data. 现在,在您的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);
     });
});

Note here i have called the Servlet from the Same page using JQuery AJAX. 请注意,这里我使用JQuery AJAX从同一页面调用了Servlet。 The above code calls the servlet and alerts the data that the jsonarray returns. 上面的代码调用servlet,并警告jsonarray返回的数据。

For more detailed explaination, you may try this link as mentioned in the comment above. 有关更详细的说明,您可以尝试上面评论中提到的此链接

Hope this solves your query :) 希望这可以解决您的查询:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM