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>