|
In a previous blog entry I wrote about building RESTful Web Services using Java and the JAX-WS library. As a result of JAX-WS being designed specifically as a generic, all-purpose Web Service tool that can do both WSDL and RESTful type web services, I think the syntax lacks a little bit of that simplicity that I'm striving for. That kind of simplicity I've already seen is possible using WCF's RESTful attributes and I'm constantly on the lookout for cooler, simpler, better RESTful stacks. I can't help it, I'm completely obsessed.
So this is when I found JAX-RS. You can find implementations of this in Metro, hosted by Java's GlassFish container...but you can also find a really good implementation of it in the latest snapshot of the CXF framework.
To create a RESTful Web Service using JAX-RS, all you really need to do is create a class that will be your service and then your container (in my case Tomcat) and CXF do the rest. Here's a snippet of a sample class from a CRM service that has been decorated with JAX-RS/RESTful attributes:
// misc imports
@Path("/")
@Produces("application/xml")
public class CustomerService implements ApplicationContextAware {
// private member variables go here.
@GET
@Path("/customers")
public CustomerList getCustomers() {
// code to build customer list goes here
}
@GET
@Path("/customers/{customerId}")
public Customer getCustomer(@PathParam("customerId") String customerId) {
// code to fetch individual customer goes here
}
}
As you can see, there's a /customers URL and a /customers/### URL that allow you to retrieve either a full list of customers or a payload for a single customer. It's pretty self-explanatory from just looking at the code (which I like). One thing you'll notice is that the service class is application context aware, which means I'm going to be creating an instance of my JAX-RS server using spring. Below is a little snippet of the spring.xml file that instantiates (or injects, depending on who you ask) the JAX-RS server:
<bean id="crmService" class="com.dotnetaddict.samples.CustomerService"
init-method="init"/>
<jaxrs:server id="customerServerJaxRs" address="/crm">
<jaxrs:serviceBeans>
<ref bean="crmService"/>
</jaxrs:serviceBeans>
</jaxrs:server>
In short, this is yet another way that you can build RESTful Web Services using Java. I prefer the JAX-RS way of doing things over the JAX-WS way of doing things mostly because the syntax is specifically designed to be RESTful and RESTful isn't just some kind of add-on that you can tack on to an otherwise WSDL-type Web Service.
However, my quest for the simplest and easiest RESTful syntax that is also applicable in the enterprise isn't over yet :)
So to clarify, the above code combined with the above spring.xml file
creates a URL at (server)/crm/customers and another URL at
(server)/crm/customers/(id)