如何将 JSP 中的 ResultSet 对象发送回 HTML (JavaScript)?

发布于 2024-10-06 20:26:40 字数 261 浏览 1 评论 0 原文

我有一个查询 MySQL 数据库的 JSP 页面,我想将 Resultset 对象作为响应对象发送到 HTML 页面?我需要结果集对象来填充表格和图表。

  1. 如何将 resultSet 对象转换为 JavaScript 对象?

  2. 如何将 resultSet 对象从 JSP 发送到 HTML? (我的意思是语法)

我使用 get xmlHTTPrequest 来调用 JSP 页面

I have a JSP page that queries a MySQL database, I want to send the Resultset object to an HTML page as a response object? I need the resultset object to populate a table and a chart.

  1. How do I cast the resultSet object into a javascript object?

  2. How do I send a resultSet object from JSP to HTML? (I mean the syntax)

I am using get xmlHTTPrequest to call the JSP page

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人九事 2024-10-13 20:26:40

不要使用 JSP。使用 Servlet 查询数据库,获取带有结果的 List 并将其转换为 JS 可以无缝使用的 JSON 字符串。

首先创建一个 javabean 类,它代表数据库表的一行。例如产品

public class Product {
    private Long id;
    private String name;
    private String description;
    private BigDecimal price;

    // Add/generate c'tors, getters, setters and other boilerplate.
}

创建一个 DAO 类,该类触发查询并将 ResultSet 映射到 List

public class ProductDAO {

    // ...

    public List<Product> find(String search) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Product> products = new ArrayList<Product>();

        try {
            connection = database.getConnection();
            statement = connection.prepareStatement(SQL_FIND);
            statement.setString(1, search);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Product product = new Product();
                product.setId(resultSet.getLong("id"));
                product.setName(resultSet.getString("name"));
                product.setDescription(resultSet.getString("description"));
                product.setPrice(resultSet.getBigDecimal("price"));
                products.add(product);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }

        return products;
    }
}

然后创建一个 Servlet 类,该类使用 DAO 类来获取产品,并在 Google Gson

public class ProductServlet extends HttpServlet {

    // ...

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Product> products = productDAO.find(request.getParameter("search"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new Gson().toJson(products));
        } catch (SQLException e) {
            throw new ServletException("DB error", e);
        }
    }
}

web.xml 中将这个 servlet 映射到 /productsurl-pattern 上,并在 JavaScript 中调用它,如下所示(我使用 jQuery 因为它消除了跨浏览器敏感的样板文件,因此您最终的 JavaScript 代码减少了 10 倍)。

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4407861</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#searchform').submit(function() {
                    $.getJSON("products", $(this).serialize(), function(products) {
                        var table = $('#resulttable');
                        $.each(products, function(index, product) {
                            $('<tr>').appendTo(table)
                                .append($('<td>').text(product.id))
                                .append($('<td>').text(product.name))
                                .append($('<td>').text(product.description))
                                .append($('<td>').text(product.price));
                        });
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <form id="searchform">
            <input type="text" name="search">
            <input type="submit">
        </form>
        <table id="resulttable"></table>
    </body>
</html>

Don't use JSP. Use a Servlet which queries the DB, obtains a List with results and converts it to a JSON string which JS can seamlessly use.

First create a javabean class which represents a single row of the DB table. E.g. Product.

public class Product {
    private Long id;
    private String name;
    private String description;
    private BigDecimal price;

    // Add/generate c'tors, getters, setters and other boilerplate.
}

The create a DAO class which fires the query and maps the ResultSet to a List<Product>.

public class ProductDAO {

    // ...

    public List<Product> find(String search) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Product> products = new ArrayList<Product>();

        try {
            connection = database.getConnection();
            statement = connection.prepareStatement(SQL_FIND);
            statement.setString(1, search);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Product product = new Product();
                product.setId(resultSet.getLong("id"));
                product.setName(resultSet.getString("name"));
                product.setDescription(resultSet.getString("description"));
                product.setPrice(resultSet.getBigDecimal("price"));
                products.add(product);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }

        return products;
    }
}

Then create a Servlet class which uses the DAO class to obtain the products and converts it to a JSON string with a little help of Google Gson.

public class ProductServlet extends HttpServlet {

    // ...

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Product> products = productDAO.find(request.getParameter("search"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(new Gson().toJson(products));
        } catch (SQLException e) {
            throw new ServletException("DB error", e);
        }
    }
}

Map this servlet in web.xml on an url-pattern of /products and call it in JavaScript as follows (I am using jQuery since it eliminates crossbrowsersensitive boilerplate so that you end up with 10 times less JavaScript code).

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4407861</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('#searchform').submit(function() {
                    $.getJSON("products", $(this).serialize(), function(products) {
                        var table = $('#resulttable');
                        $.each(products, function(index, product) {
                            $('<tr>').appendTo(table)
                                .append($('<td>').text(product.id))
                                .append($('<td>').text(product.name))
                                .append($('<td>').text(product.description))
                                .append($('<td>').text(product.price));
                        });
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <form id="searchform">
            <input type="text" name="search">
            <input type="submit">
        </form>
        <table id="resulttable"></table>
    </body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文