I'm trying to edit my create method in my REST webservice so it should return the newly created ID from the object. I've been trying for the past two days but I must be doing something terribly wrong...
This is the edited create method on the server side:
@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());
}
It is based on a (by netbeans) generated count() method as shown below:
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
If I do a request from my client to add a new Users object, it works like as expected. The new user is beeing added to the database. In the GlassFish server log, I see the newly created ID shown by the System.out.println command. However, if I do a test via the TestRestful Web Services in netbeans, paste the client generated XML code at the correct window and hit the TEST button, I receive a HTTP Status 415 - Unsupported Media Type error.
I did some research and found this question. So my guess instead of returning a String, I should return a Response object with a 201 CREATED status and adjust the header or something? I checked out the spring example but as I am not using spring, I have no clue how to adjust the create2 method code... however I did a try but I'm missing some pieces:
@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();
}
I hope that I'm on the right track. Sorry for the long post, hope someone can help me out here. Thanks in advance!
Edit: working example now:
@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();
}