RESTful is more an architecture style than a different technology. In server perspective, it is designed to be entirely stateless and self-contained on a per-request basis (i.e. there are no sessions). In client perspective, it's more a way of getting information in different formats via URLs with (self-documenting) path parameters instead of request parameters.
Surely you can do this with a plain vanilla servlet, but it would introduce some boilerplate code to gather the path parameters and to generate the desired response. JAX-RS is just a convenient and self-containing API which removes the need for writing all the boilerplate code yourself, resulting in minimal and more self-documenting code.
Assuming that you've a JAXB entity as model as below:
@XmlRootElement
public class Data {
@XmlElement
private Long id;
@XmlElement
private String value;
// ...
@Override
public String toString() {
return String.format("Data[id=%d,value=%s]", id, value);
}
}
And a JAX-RS resource as below:
@Path("data")
public class DataResource {
@EJB
private DataService service;
@GET
@Path("text/{id}")
@Produces(MediaType.TEXT_PLAIN)
public String getAsText(@PathParam("id") Long id) {
return String.valueOf(service.find(id));
}
@GET
@Path("xml/{id}")
@Produces(MediaType.APPLICATION_XML)
public Data getAsXml(@PathParam("id") Long id) {
return service.find(id);
}
@GET
@Path("json/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Data getAsJson(@PathParam("id") Long id) {
return service.find(id);
}
}
Then you'd already get the desired content in proper format by:
That's it. Try to do the same with a single plain vanilla Servlet :) Please note that SOAP essentially also goes over HTTP. It's basically an extra XML layer over HTTP, not a different network protocol.
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…