Reputation: 51
I want to make a Post to Jersey Rest service. What is the standard way of doing this?
@Post
@Consumes(MediaType.Application_xml)
public Response method(??){}
Upvotes: 5
Views: 15914
Reputation: 931
Suppose you have a java bean say an employee bean such as. Add the tags to tell
@XmlRootElement (name = "Employee")
public class Employee {
String employeeName;
@XmlElement
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
@XmlRootElement tells that this will be the main tag in xml. In this case you can specify a name for the main tag as well.
@XmlElement tells that this would be the sub tag inside the root tag
Say, the sample xml that will come as a part of body in the post request will look something like
<?xml version="1.0" encoding="UTF-8"?>
<Employee>
<employeeName>Jack</employeeName>
</Employee>
When writing a webservice to acccept such an xml we can write the following method.
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response getEmployee(Employee employee) {
employee.setEmployeeName(employee.getEmployeeName() + " Welcome");
return Response.status(Status.OK).entity(employee).build();
}
On calling this service, you will get the following xml as part of the response.
<Employee>
<employeeName> Jack Welcome </employeeName>
</Employee>
using @Xml...annotations, it becomes very easy to unmarshal and marshal the request and response objects.
Similar approach can be taken for JSON input as well as JSON output by just using the MediaType.APPLICATION_JSON instead of APPLICATION_XML
So for an xml as input, you can get an xml as an output as part of the http response. Hope this helps.
Upvotes: 6
Reputation: 149017
Below is an example of a post operation:
@POST
@Consumes({"application/xml", "application/json"})
public Response create(@Context UriInfo uriInfo, Customer entity) {
entityManager.persist(entity);
entityManager.flush();
UriBuilder uriBuilder = uriBuiler.path(String.valueOf(entity.getId()));
return Response.created(uriBuilder.build()).build();
}
Upvotes: 4