我正在尝试使用Jersey来创建RESTful资源。我想要的是点击一个链接,应该访问BookResource并显示数据库中的书籍列表。现在我想要的只是JavaScript中的函数来抛出它确实进行ajax调用的警报。但是,它进入request.fail循环并且没有做任何事情。
BookResource.java
import com.helper.BooksHelper;
import com.servlets.Book;
@Path("/books")
public class BookResource {
@GET
@Path("/allBooks")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
BooksHelper bookHelper = new BooksHelper();
ArrayList<Book> listOfBooks = bookHelper.getListOfBooks();
ResponseBuilder responseBuilder = Response.status(Status.OK);
responseBuilder.entity(listOfBooks);
Response response = responseBuilder.build();
return response;
}
的index.jsp
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="list.js"></script>
</head>
<body>
<h2>Library Management System</h2>
<h3>Welcome, ${username}</h3>
<p>List of books in library <a href="" onclick="libBooks();">Click Here</a></p>
<div id="bookList"></div>
<p>Visit <a href="http://jersey.java.net">Project Jersey website</a>
for more information on Jersey!
</body>
</html>
list.js
function libBooks(){
alert("Inside js");
//The above alert is displayed
var requestData = {
"dataType": "json",
"type": "GET",
"url": "http://localhost:8080/library/webapi/books/allBooks"
};
var request = $.ajax(requestData);
alert("Ajax call made");
//The above alert is displayed
request.success(function(data) {
alert("Inside done function");
//The above alert is not displayed
var dataReceived =data.listOfBooks;
var numOfItems = dataReceived.length;
alert(numOfItems);
});
request.fail(function(jqXHR, status, errorMessage) {
if((errorMessage = $.trim(errorMessage)) === "") {
alert("An unspecified error occurred. Check the server error log for details.");
}
else {
alert("An error occurred: " + errorMessage);
//The above alert is displayed
}
});
}
的web.xml
<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>org.-------(hidden).library</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>
我想在index.jsp本身上发出警报,确认ajax调用成功。我开始申请的网址是http://localhost:8080/library/login.jsp 然后成功登录URL更改为http://localhost:8080/library/login,这是我有链接的地方,
库中的书籍列表点击此处
,但点击它除了警报没有任何反应&#34;内部js&#34;和&#34; Ajax调用&#34;。我在控制台开发人员工具中遇到错误,这些工具是&#34; http://localhost:8080/library/webapi/books/allBooks&#34;无法找到。我究竟做错了什么。我在网上跟踪了很多例子,这就是他们如何做到这一点。网址不正确吗?任何帮助将不胜感激。谢谢。