findAll()返回一个空白页面--JavaScript,JSON

时间:2017-04-25 15:37:25

标签: javascript json jersey

我正在做一个球衣项目,我有很多问题。我使用java作为后端,使用javaScript作为前端。就我在Tomcat上运行我的index.html文件而言,空白表单旁边没有任何内容。 findAll是Tomcat Server控制台中唯一写下来的东西。如果有人能帮助我,我将非常感激。我觉得毫无意义。以下是我的整个代码。

BookResources.java

package com.bookstrore;

import java.util.List;


import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.bookstrore.model.Book;
import com.bookstrore.repository.BookDAO;

@Path("/book")
public class BookResources {

    BookDAO dao = new BookDAO();

    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Book> findAll() {
        System.out.println("findAll");
        return dao.findAll();
    }



}

Book.java

package com.bookstrore.model;

import javax.persistence.Column;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

//@Entity
//@Table(name="book")
@XmlRootElement
public class Book {

//@Id
//@GeneratedValue(strategy=GenerationType.IDENTITY)
private int book_id;

private String book_title;

private String book_author;

private String book_description;

private int book_price;


public int getBook_id() {
    return book_id;
}
public void setBook_id(int book_id) {
    this.book_id = book_id;
}
public String getBook_title() {
    return book_title;
}
public void setBook_title(String book_title) {
    this.book_title = book_title;
}
public String getBook_author() {
    return book_author;
}
public void setBook_author(String book_author) {
    this.book_author = book_author;
}
public String getBook_description() {
    return book_description;
}
public void setBook_description(String book_description) {
    this.book_description = book_description;
}
public int getBook_price() {
    return book_price;
}
public void setBook_price(int book_price) {
    this.book_price = book_price;
}


}

BookDAO.java

package com.bookstrore.repository;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.bookstrore.auth.ConnectionHelper;
import com.bookstrore.model.Book;


public class BookDAO {

    public List<Book> findAll() {
        List<Book> list = new ArrayList<Book>();
        Connection c = null;
        String sql = "SELECT * FROM book ORDER BY book_title";
        try {
            c = ConnectionHelper.getConnection();
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                list.add(processRow(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            ConnectionHelper.close(c);
        }
        return list;
    }

}

ConnectionHelper.java

package com.bookstrore.auth;



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class ConnectionHelper
{
    private String url;
    private static ConnectionHelper instance;

    private ConnectionHelper()
    {
        String driver = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            url = "jdbc:mysql://localhost/directory?user=root";
            ResourceBundle bundle = ResourceBundle.getBundle("ebooks");
            driver = bundle.getString("jdbc.driver");
            Class.forName(driver);
            url=bundle.getString("jdbc.url");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        if (instance == null) {
            instance = new ConnectionHelper();
        }
        try {
            return DriverManager.getConnection(instance.url);
        } catch (SQLException e) {
            throw e;
        }
    }

    public static void close(Connection connection)
    {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.bookstrore</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

main.js

// The root URL for the RESTful services
var rootURL = "http://localhost:8080/BookStore/webapi/book";

var currentBook;

// Retrieve wine list when application starts 
findAll();

// Nothing to delete in initial application state
$('#btnDelete').hide();

$('#btnSearch').click(function() {
    search($('#searchKey').val());
    return false;
});

// Trigger search when pressing 'Return' on search key input field
$('#searchKey').keypress(function(e){
    if(e.which == 13) {
        search($('#searchKey').val());
        e.preventDefault();
        return false;
    }
});




$('#btnAdd').click(function() {
    newBook();
    return false;
});

$('#btnSave').click(function() {
    if ($('#book_id').val() == '')
        addBook();
    else
        updateBook();
    return false;
});

$('#btnDelete').click(function() {
    deleteBook();
    return false;
});

$('#bookList b').live('click', function() {
    findById($(this).data('identity'));
});





function newBook() {
    $('#btnDelete').hide();
    currentBook = {};
    renderDetails(currentBook); // Display empty form
}

function findAll() {
    console.log('findAll');
    $.ajax({
        type: 'GET',
        url: rootURL,
        dataType: "json", // data type of response
        success: renderList
    });
}

function findByName(searchKey) {
    console.log('findByName: ' + searchKey);
    $.ajax({
        type: 'GET',
        url: rootURL + '/search/' + searchKey,
        dataType: "json",
        success: renderList 
    });
}

function findById(id) {
    console.log('findById: ' + id);
    $.ajax({
        type: 'GET',
        url: rootURL + '/' + id,
        dataType: "json",
        success: function(data){
            $('#btnDelete').show();
            console.log('findById success: ' + data.name);
            currentBook = data;
            renderDetails(currentWine);
        }
    });
}

function addBook() {
    console.log('addBook');
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: rootURL,
        dataType: "json",
        data: formToJSON(),
        success: function(data, textStatus, jqXHR){
            alert('Book created successfully');
            $('#btnDelete').show();
            $('#book_id').val(data.id);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('addBook error: ' + textStatus);
        }
    });
}

function updateBook() {
    console.log('updateBook');
    $.ajax({
        type: 'PUT',
        contentType: 'application/json',
        url: rootURL + '/' + $('#book_id').val(),
        dataType: "json",
        data: formToJSON(),
        success: function(data, textStatus, jqXHR){
            alert('Book updated successfully');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('updateBook error: ' + textStatus);
        }
    });
}

function deleteBook() {
    console.log('deleteBook');
    $.ajax({
        type: 'DELETE',
        url: rootURL + '/' + $('#book_id').val(),
        success: function(data, textStatus, jqXHR){
            alert('Book deleted successfully');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('deleteBook error');
        }
    });
}

function renderList(data) {
    // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
    var list = data == null ? [] : (data instanceof Array ? data : [data]);

    $('#bookList li').remove();
    $.each(list, function(index, book) {
        $('#bookList').append('<li><a href="#" data-identity="' + book.book_id + '">'+book.book_title+'</a></li>');
    });
}

function renderDetails(book) {
    $('#book_id').val(book_id);
    $('#book_title').val(book_title);
    $('#book_author').val(book_author);
    $('#book_description').val(book_description);
    $('#book_price').val(book_price);

}

// Helper function to serialize all the form fields into a JSON string
function formToJSON() {
    var book_id = $('#book_id').val();
    return JSON.stringify({
        "book_id": book_id == "" ? null : book_id, 
        "book_title": $('#book_title').val(), 
        "book_author": $('#book_author').val(),
        "book_description": $('#book_description').val(),
        "book_price": $('#book_price').val(),

        });
}

的index.html

<!DOCTYPE HTML>
<html>
<head>
<title>BookStore</title>
<link rel="stylesheet" href="css/styles.css" />
</head>

<body>

<div class="header">
    <input type="text" id="searchKey"/>
    <button id="btnSearch">Search</button>
    <button id="btnAdd">New Book</button>
</div>


<div class="leftArea">
<ul id="bookList"></ul>
</div>

<form id="bookForm">

<div class="mainArea">

<label>Id:</label>
<input id="book_id" name="book_id" type="text" disabled />

<label>Title:</label>
<input type="text" id="book_title" name="book_title" required>

<label>Author:</label>
<input type="text" id="book_author" name="book_author"/>

<label>Description:</label>
<textarea id="book_description" name="book_description"></textarea>

<label>Price:</label>
<input type="text" id="book_price" name="book_price"/>



<button id="btnSave">Save</button>
<button id="btnDelete">Delete</button>

</div>



</form>

<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/main.js"></script>

</body>
</html>

解决方案:

那里只是一个不匹配的词。我解决了谢谢!

0 个答案:

没有答案