我知道有很多这样的帖子,但由于我对 REST 和 JQuery 都是新手,所以我无法真正让它发挥作用:
我正在使用带有 Java 5 的 REST-WS,我可以调用它并使用“Poster”(用于测试它的 firefox 插件)返回结果。当我调用下面的 URL 时,我应该通过调用下面显示的资源类中的方法“getCustomer”来让员工在地图中按“0”的顺序排列。
虽然我无法获得结果并在使用 jQuery 并返回 JSON 时收到错误“未知”,但当我从正文如下的 html 页面调用 REST 时:
<body>
jQuery to REST <br><br>
<a href="http://jquery.com/">jQuery</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function (){
$.ajax({
type: "GET",
url: "http://localhost:8081/RestDemo/services/customers/0",
dataType: "json",
success: function (data) {
alert(data.name);
},
error: function(e){
alert("Error: " + e);
}
});
});
});
</script>
<br>
<br>
<button>Return Customer</button>
</body>
这是我的资源类:
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.spi.resource.Singleton;
@Produces("application/xml")
@Path("customers")
@Singleton
@XmlRootElement(name = "customers")
public class CustomerResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
@GET
@XmlElement(name = "customer")
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
@GET
@Path("/{id}")
@Produces("application/json")
public String getCustomer(@PathParam("id") int cId) {
return "{\"name\": \"unknown\", \"address\": -1}"; //customerMap.get(cId);
}
@POST
@Path("add")
@Produces("text/html")
@Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
我感谢任何人的帮助,
谢谢!