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 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:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With