Jersey Consumes XML post

不羁的心 提交于 2019-12-21 17:36:02

问题


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(??){}

回答1:


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.




回答2:


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();
}


来源:https://stackoverflow.com/questions/3203989/jersey-consumes-xml-post

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!