我正在尝试在我的 REST Web 服务中编辑我的 create 方法,以便它应该从对象返回新创建的 ID。过去两天我一直在尝试,但我一定是做错了什么……
这是服务器端编辑后的创建方法:
@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 状态 415 - 不支持的媒体类型错误。
我做了一些研究,发现了这个问题。所以我猜我应该返回一个 201 CREATED 状态的响应对象,而不是返回一个字符串,并调整标题或什么?我查看了 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();
}