gpt4 book ai didi

java - 将 JSON 数组从 Java Servlet 传递到 HTML

转载 作者:行者123 更新时间:2023-12-03 12:07:14 25 4
gpt4 key购买 nike

我正在开发一个项目,该项目涉及从 MySQL 数据库检索数据并对其进行分页。我正在使用 JSON AJAX 和 JavaScript。我是 JSON 和 AJAX 新手。我已从数据库获取数据并使用 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();
}
}
}
}

最佳答案

如果我是正确的,我将进行如下更改(至少我已经为我的代码做了):

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 数组中。

现在其次,在响应部分中,您需要绑定(bind) JSONArray obj,而不是直接将重定向响应发送到 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正如上面评论中提到的。

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

关于java - 将 JSON 数组从 Java Servlet 传递到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com