传递JSON数组从Java Servlet来HTML [英] Passing JSON Array from Java Servlet to HTML

查看:161
本文介绍了传递JSON数组从Java Servlet来HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的这涉及到从MySQL数据库中检索数据的项目,分页它。我使用JSON Ajax和JavaScript。我是新来的JSON和AJAX。我从数据库中获得的数据和使用servlet存储在JSON对象。我的问题是,如何从我的Servlet到目标HTML文件中传递这些数据? 如果我会用JavaScript,然后怎么样?

Servlet的文件

 进口java.io.IOException异常;
导入的java.sql *。
进口的java.io.PrintWriter;
进口javax.servlet.http.HttpServlet的;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;
进口org.json.simple *。

公共类DbServlet延伸的HttpServlet实现DatabaseConstants {
    私有静态最后长的serialVersionUID = 1L;

    保护无效的doPost(HttpServletRequest的要求,
            HttpServletResponse的响应){
        字符串jdbcDriver,JDBCURL,用户名,密码,查询;
        字符串错误code = NULL;
        INT I = 0;
        INT列数= 0;

        response.setContentType(应用/ JSON);

        jdbcDriver =的request.getParameter(JDBC_DRIVER);
        JDBCURL =的request.getParameter(JDBC_URL);
        用户名=的request.getParameter(用户名);
        密码=的request.getParameter(密码);
        查询=的request.getParameter(查询);

        连接CON = NULL;
        PrintWriter的输出= NULL;
        声明语句= NULL;
        结果集的ResultSet = NULL;

        的JSONObject的JSONObject = NULL,sendDBJsonObject = NULL;
        JSONArray dbResultJSON;

        尝试 {
            OUT = response.getWriter();

            的Class.forName(jdbcDriver);
            的System.out.println(试图建立连接。);
            CON =的DriverManager.getConnection(JDBCURL,用户名,密码);
            的System.out.println(连接成功。);

            语句= con.createStatement();
            结果集= stmt.executeQuery(查询);

            如果(!resultSet.first()){
                通过out.println(&其中; H3>有在所请求的数据库中没有行&所述; / H3>中);
            } 其他 {

                ResultSetMetaData的RSMD = ResultSet.getMetaData得到();

                列数= rsmd.getColumnCount();

                dbResultJSON =新JSONArray();

                resultSet.beforeFirst();
                而(ResultSet.next时()){
                    //通过out.println(&其中; TR>中);
                    的JSONObject =新的JSONObject();
                    对于(i = 1; I< =列数;我++){
                        jsonObject.put(rsmd.getColumnLabel(ⅰ),
                                (resultSet.getString(一)== NULL?空
                                        :resultSet.getString(ⅰ)));
                    }
                    dbResultJSON.add(的JSONObject);
                }
                sendDBJsonObject =新的JSONObject();
                sendDBJsonObject.put(DBRESULTS,dbResultJSON);
                / *
                 *通过out.println(< /表>);通过out.println(<选择>+
                 *<期权价值= \十一五\> 5℃/选项>中+
                 *<期权价值= \十\> 10< /选项>中+
                 *<期权价值= \二十\> 20℃/选项>中+
                 *<期权价值= \五十\> 50℃/选项>中+< /选择&g​​t;中);
                 * /
                response.sendRedirect(result.html);
            }
        }赶上(的SQLException | ClassNotFoundException异常E){

            如果(jdbcDriver.isEmpty())
                错误code =SQL错误请输入一个有效的SQL驱动程序。
            否则,如果(jdbcURL.isEmpty())
                错误code =SQL错误请输入一个有效的SQL网址。
            否则,如果(username.isEmpty())
                错误code =访问被拒绝请输入有效的用户名。;
            否则,如果(password.isEmpty())
                错误code =访问被拒绝请输入正确的密码。
            否则,如果(query.isEmpty())
                错误code =SQL错误无法发出空查询。
            其他
                错误code = e.getLocalizedMessage();

            尝试 {
                response.sendError(500,错误code);
            }赶上(IOException异常IOE){
                ioE.printStackTrace();
            }

        }赶上(IOException异常IOE){
            ioE.printStackTrace();
        } 最后 {
            如果(结果集!= NULL){
                尝试 {
                    resultSet.close();
                }赶上(的SQLException E){
                    e.printStackTrace();
                }
            }
            如果(stmt是!= NULL)
                尝试 {
                    stmt.close();
                }赶上(E1的SQLException){
                    e1.printStackTrace();
                }
            如果(满分!= NULL)
                out.close();
            如果(CON!= NULL)
                尝试 {
                    con.close();
                }赶上(的SQLException E){
                    e.printStackTrace();
                }
        }
    }
}
 

解决方案

如果我是正确的,我会做如下的(至少我已经做了我的code)的修改

 的JSONObject工作=新的JSONObject(); //创建一个JSON对象OBJ。
JSONArray jArray =新JSONArray(); //创建一个JSON数组OBJ。

preparedStatement PS =康恩prepareStatement(SQL)。

结果集RS = ps.executeQuery();

而(先将rs.next()){

        / *带有可变进JSON的OBJ *分配结果集/
        job.put(rs_val_one,rs.getString(1));
        job.put(rs_val_two,rs.getString(2));

        jArray.put(工作); //添加JSON OBJ(作业)到JSON array.This将使它更容易获取每步的结果。

        job.clear(); //清除OBJ。从存储器

}
 

嗯,你已经做得最多的部分正确的,它似乎。唯一的区别在上面的部分我已经分配的JSONObject对象转换成JSON数组。

现在二,在响应部分,而不是直接发送重定向响应HTML / JSP页面,你需要绑定JSONArray OBJ。数据到响应。因此,而不是

  response.sendRedirect(result.html);
 

做到这一点:

  response.getWriter()写(jArray.toString())。
 

这需要在Servlet部分的照顾。现在,在你的 result.html 页,你需要添加下面的code序来获取jArray数据。

  / **调用使用jQuery的getJSON方法的servlet
  * @url:Servlet的URL
  * @data:价值Servlet返回
* /
$ .getJSON(URL,功能(数据){

      //遍历每个值,Servlet返回
      $每个(数据,功能(键,值){
               警报(v​​alue.rs_val_one); //警报在Sevlet的的JSONObject设置的值。
               警报(v​​alue.rs_val_two);
     });
});
 

请注意我在这里呼吁,从使用JQuery AJAX同一个页面中的Servlet。上述code调用servlet和警报数据的jsonarray回报。

有关更详细的解释,你可以试试这个链接中提到的上面的注释。

希望这能解决您的查询:)

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

解决方案

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 :)

这篇关于传递JSON数组从Java Servlet来HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆