开发者

REST/XML Api with Java

开发者 https://www.devze.com 2023-03-09 05:43 出处:网络
I am trying to provide a REST/XML Api programmed in Java. The application is given a parameter and will then return XML content via HTTP.

I am trying to provide a REST/XML Api programmed in Java. The application is given a parameter and will then return XML content via HTTP.

In PHP the way I would solve it by having a rest_api.php file which is provided the parameter &string=helloworld by the application using my api, then I read this开发者_StackOverflow中文版 string, do calculations or searches with it, modify the data to meet my XML schema and reply this data an echo which sends it back with the HTTP response.

How do I do this properly with Java?


Two Java extensions work wonderfully in concert to this end:

  • JAX-RS (reference implementation Jersey)
  • JAXB (reference implementation Metro)

Both are included with the Glassfish Java EE 5 and 6 reference implementation.

In short, JAX-RS lets you declare a plain method as a web service by adding one of the @GET, @POST, @PUT or @DELETE annotations. JAX-RS also has annotations for automatic parsing of path and URL query parameters, and it takes care of constructing the proper response objects in most cases.

JAXB automatically translates plain objects (POJOs) to and from XML by adding @XmlRootElement, @XmlElement, @XmlID, etc. When combined with JAX-RS, marshalling and unmarshalling is done transparently.

For example:

// POJO with JAXB annotations

@XmlRootElement(name = "sensor")
public class MyObject {
    @XmlID
    @XmlElement
    private String id;

    @XmlAttribute
    private String name;

    @XmlElement(name = "sensor-value")
    private Integer value;

    @XmlTransient // don't translate to XML
    private Double computedValue;

    // ...getters and setters
}


// POJO with REST interface

@Path("/mywebservice")
public class MyWebService {
    @EJB
    MySensorController controller;

    @GET
    @Produces("application/xml")
    public MyObject getCurrentSensorValue(@QueryParam("ID") String id) {
        // automatic unmarshalling from MyObject to XML
        return controller.getSensorValue(id);
    }
}

The resulting XML will look something like this:

<sensor name="foo">
    <id>123</id>
    <sensor-value>42</sensor-value>
</sensor>


I personally have used both,

  • the Restlet framework as well as
  • Apache Jersey

which I can both recommend. I found Restlet a tad easier to start with, but Jersey offers the better integration possibilities (at least for how I used it).


The RESTlet framework should be a pretty good start


I haven't tried Restlet or Jersey, but I've been very pleased with Apache Wink. It's worked well in our production environment without issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消