【发布时间】:2012-10-19 09:27:23
【问题描述】:
我正在尝试在我的 REST Web 服务中编辑我的 create 方法,以便它应该从对象返回新创建的 ID。这两天我一直在努力,但我一定是做错了什么……
这是服务器端编辑好的create方法:
@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain")
public String create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
System.out.println("new id: " + entity.getId());
return String.valueOf(entity.getId());
}
它基于(由 netbeans 生成的)count() 方法,如下所示:
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
如果我从我的客户端请求添加一个新的用户对象,它会按预期工作。新用户正在添加到数据库中。在 GlassFish 服务器日志中,我看到 System.out.println 命令显示的新创建的 ID。但是,如果我通过 netbeans 中的 TestRestful Web 服务进行测试,将客户端生成的 XML 代码粘贴到正确的窗口并点击 TEST 按钮,我会收到 HTTP Status 415 - Unsupported Media Type 错误。
我做了一些研究,发现了this 的问题。所以我的猜测不是返回一个字符串,我应该返回一个 201 已创建状态的响应对象并调整标题或什么?我查看了 spring 示例,但由于我没有使用 spring,所以我不知道如何调整 create2 方法代码......但是我尝试了但我遗漏了一些部分:
@POST
@Consumes({"application/xml", "application/json"})
@Path("withID")
@Produces("text/plain") //should this change to application/xml?
public Response create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
System.out.println("new id: " + entity.getId());
//Response response = Response.created(... + "withID/" + entity.getId()); //response need an URI, can I get this through the entity object?
return Response.status(200).entity(entity.getId().toString()).build();
}
我希望我走在正确的轨道上。对不起,很长的帖子,希望有人可以在这里帮助我。提前致谢!
编辑:现在的工作示例:
@POST
@Consumes({"application/xml"})
@Path("withID")
@Produces({"application/xml"})
public Response create2(Users entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
return Response.status(201).entity(entity.getId().toString()).build();
}
【问题讨论】:
-
您不需要调整任何标题。 Response.created() 自动将您提供给 http 响应的 URI 作为“位置”标头。所以看起来你已经有了解决方案。
-
嗨 Pavel,我只在
javax.ws.rs.core.Response中找到以下方法public static Response.ResponseBuilder created(URI location)。为创建的资源创建一个新的 ResponseBuilder,使用提供的值设置位置标头。
标签: java web-services rest jersey jax-rs