[英]Posting data to a dropwizard resource?
I am trying to establish how I might post data to my dropwizard resource. 我正在尝试确定如何将数据发布到我的dropwizard资源中。
Say for example I have the following resource : 例如,我有以下资源:
@GET
@Timed
@Path("/update/{id}")
public int updateRecord( @PathParam("id") int id) throws JsonParseException, JsonMappingException, IOException
// Logic here I guess?!
// Returning 0 to kill the error regarding not returning antyhing in my IDE.
return 0;
}
now I would like to be able to do a jquery post, such as : 现在,我希望能够执行一个jquery帖子,例如:
$.post(" http://localhost:8080/update/1/ ", jsonUpdateString); $ .post(“ http:// localhost:8080 / update / 1 / ”,jsonUpdateString);
for the record "jsonUpdateString" is a stringified JSON array - I already know how to map that to a java data structure, as I have done it hardcoded before - I just need to know what I need to add to my resource to actually use "jsonUpdateString" in my java side. 因为记录“ jsonUpdateString”是一个字符串化的JSON数组-我已经知道如何将其映射到java数据结构,就像我之前对其进行硬编码一样-我只需要知道我需要添加到资源中才能实际使用“ jsonUpdateString”在我的Java端。
Something like this should work: 这样的事情应该起作用:
static class Entity {
@JsonProperty String name;
}
@POST
@Timed
@Path("update/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public int updateRecord(@PathParam("id") int id, List<Entity> entities) {
// Do something with entities...
return 0;
}
Which you can test with: 您可以使用以下方法进行测试:
curl -H "Content-Type: application/json" --data '[{"name":"foo"}]' http://localhost:8080/update/1
A few things: 一些东西:
If your method has one unannotated argument ( entities
, in this case) Jersey will attempt to map the request entity to this object. 如果你的方法有一个未加论证(
entities
,在这种情况下),新泽西州将尝试请求实体映射到该对象。
Let Jersey / Jackson do the JSON conversion for you (see Entity
). 让Jersey / Jackson为您执行JSON转换(请参阅
Entity
)。
Make sure that your JQuery client is setting the request header Content-Type: application/json
. 确保您的JQuery客户端设置了请求标头
Content-Type: application/json
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.