【问题标题】:How to send a ResultSet object in JSP back to HTML (JavaScript)?如何将 JSP 中的 ResultSet 对象发送回 HTML (JavaScript)?
【发布时间】:2011-05-23 09:54:59
【问题描述】:

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

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

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

我正在使用 get xmlHTTPrequest 来调用 JSP 页面

【问题讨论】:

    标签: javascript html jsp jdbc


    【解决方案1】:

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

    首先创建一个 javabean 类,它代表 DB 表的单行。例如。 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.
    }
    

    创建一个触发查询并将ResultSet 映射到List<Product> 的DAO 类。

    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 的帮助下将其转换为 JSON 字符串。

    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 的url-pattern 或/products 上映射此servlet,并在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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 2015-06-10
      • 2016-10-26
      • 1970-01-01
      • 2017-01-20
      相关资源
      最近更新 更多