【发布时间】:2012-06-03 09:13:16
【问题描述】:
我的资源类中有以下方法用于 Java 中的 REST 服务。
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Player createCustomer(Customer customer)
{
System.out.println("Request for Create");
System.out.println(""+customer.getID()+"\n"+customer.getTableID()+"\n"+customer.getCustNick());
//Above statement should print the details I send via JSON object
//return custdao.create(customer); //Want to call this to add new "customer" into database table.
return player;
}
并按照我在填写表单中的输入字段并单击创建按钮时调用的 jQuery 方法。
function createEntry() {
var formData = JSON.stringify({
"ID" : $("input[name='txtID']").val(),
"tableID" : $("input[name='txtTableID']").val(),
"custNick" : $("input[name='txtNick']").val()
});
console.log(formData); //Just to see if form details are JSON encoded.
$.ajax({
type: "POST",
contentType: "application/json",
url: baseURL,
dataType: "json",
data: formData,
success: function(data) {
console.log("Customer Added!");
$("div.response").append("<h3>New Customer ("+ $("input[name='txtNick']").val() +") Added on the Server</h3>");
}
});
}
但是在服务器上,我得到了空的“客户”对象,我在这里做错了什么?如果您需要任何进一步的详细信息(关于客户类模型),请告诉我。
更新:以下是客户类。
/*ignore imports, all required imports are included */
@XmlRootElement
public class Customer
{
private int id;
private int tableid;
private String custnick;
public int getID()
{
return id;
}
public void setID(int id)
{
this.id = id;
}
....
....
/* Similar Setter-Getter Methods for the fields */
}
我猜这个问题与我的“客户”类的 XML 模式有关,并且我在 JSON 对象中发送的节点名称与模式不匹配,这就是为什么它可能无法使用我的模型的 setter 方法映射字段的原因类,但不确定。
【问题讨论】:
-
不要手动创建表单数据,尝试使用
jQuery('#formID').serializeArray(); -
你能发布客户类吗?它适用于 XML 吗?
-
@ShaggyInjun: 我可以
serializeArray()但服务不应该通过 HTML 使用,我将创建 Java 客户端(使用 Apache HTTP 客户端)来使用服务,所以标记非常基本的,我没有使用任何表单标签。 -
@Tom:它确实在 GET 请求时以 JSON 对象的形式成功返回数据。
-
@Kush 所以它只会在你在 JavaScript 函数中构造 JSON 对象时失败。对?请向我们展示客户的注释实体类。