使用jquery和ajax显示来自mysql的数据

时间:2014-10-20 08:42:12

标签: java jquery mysql ajax json

我是初学者,我正在尝试创建一个简单的应用程序,使用JavaScript和jquery,json对象显示来自mysql的表。这并没有给我任何错误,但我迷失了如何继续。请提供您的反馈!

这是我的books.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Books {
    private int id;
    private String title;
    private String author;
    private float price;
    private int qty;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public int getQty() {
        return qty;
    }
    public void setQty(int qty) {
        this.qty = qty;
    }
    public Books(int id, String title, String author, float price, int qty) {
        super();
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
        this.qty = qty;
    }

    public Books() {

    }
    public ArrayList <Books> getBooks(ArrayList<Books>  bookList){

        Connection conn =null;
        ResultSet rset = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/ebookshop", "root", "root");
            PreparedStatement pst = (PreparedStatement) conn
                    .prepareStatement("SELECT * from books");
            rset = pst.executeQuery();

            while (rset.next()){
                Books books = new Books();
                books.setId(rset.getInt("id"));
                books.setAuthor(rset.getString("author"));
                books.setTitle(rset.getString("title"));
                books.setPrice(rset.getFloat("price"));
                books.setQty(rset.getInt("qty"));
                bookList.add(books);

            }
        } catch (SQLException e) {
            System.out.println("Could not connect to DB" + e);
        } catch (ClassNotFoundException classexpt){
            System.out.println("Couldn't find the class" + classexpt);
        }

        return bookList;

    }

}

Servlet文件:

        import java.io.IOException;
        import java.util.ArrayList;

        import javax.servlet.RequestDispatcher;
        import javax.servlet.ServletException;
        import javax.servlet.annotation.WebServlet;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;

        /**
         * Servlet implementation class BooksServlet
         */
        @WebServlet("/BooksServlet")
        public class BooksServlet extends HttpServlet {
            private static final long serialVersionUID = 1L;

            /**
             * @see HttpServlet#HttpServlet()
             */
            public BooksServlet() {
                super();
                // TODO Auto-generated constructor stub
            }

            /**
             * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
             */
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("application/json");
                Books books = new Books();
                ArrayList <Books> bookList = new ArrayList <Books>();
                bookList = books.getBooks(bookList);
                request.setAttribute("bookList", bookList);

    JSONObject obj=new JSONObject();
            JSONArray arr = new JSONArray();
            for(int i = 0 ; i< bookList.size() ; i++)
            {
                Books b = bookList.get(i);

                obj.put("id", b.getId());
                obj.put("title", b.getTitle());
                obj.put("author", b.getAuthor());
                obj.put("price", b.getPrice());
                obj.put("qty", b.getQty());

                arr.add(obj.toString());

                obj = new JSONObject();
            }

                String address = "DisplayBook.jsp";
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher(address);
                      dispatcher.forward(request, response);
            }

            /**
             * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
             */
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
            }

        }

Jsp文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    function showBook(){
        $.ajax({
            type:"GET",
            url:"BooksServlet.java",
            dataType: "json",
            data: JSON.stringify({ bookList: bookdata }),
            success:function(data){
                $("#content").html(data);
            }
        });
    }
    showBook();
});
</script>

<h3 align="center">Manage Book Details</h3>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Display All Data" /> </td>
   </tr>
</table>
<div id="content" align="center"></div>
<table>
    <tr>
        <td>id</td>
    </tr>
</table>

</body>
</html>

JSp文件是我丢失的地方。我想我是在列表中发送数据但没有收到它。或者我在servlet中发送错误的数据? 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

BooksServlet.java不应该在你的jquery url中,而应该是一个返回JSON的servlet。我不知道你试图用你的jquery代码做什么。现在它似乎已准备好接收HTML,而不是JSON。

  • 我建议您使用像firebug或类似的插件进入网络并分析您正在创建的请求/响应。
  • 我会使用DataTables来处理前端的JSON
  • 我会为后端部分示例“Struts 2结果类型JSON使用JSON解析器。

答案 1 :(得分:0)

尝试访问[server] / [context] / BooksServlet,例如localhost:8080 / myappp / BookServlet,因为/ BookServlet是servlet中的映射URL。

请参阅此@WebServlet annotation with Tomcat 7http://www.codejava.net/java-ee/servlet/webservlet-annotation-examples

顺便说一句,我仍然没有得到,你的Ajax URL转到/ BookServlet并返回json,但是那个servlet没有返回json数据。