The Source for Java Technology Collaboration
User: Password:



Brian Leonard

Brian Leonard's Blog

An Introduction to Building RESTful Web Services in Java Using NetBeans 6.0

Posted by bleonard on July 18, 2007 at 12:54 PM | Comments (9)

So, REST based web services are simpler than SOAP, right? Then why's it so difficult to create a REST based web service in Java? Using tools I can crank out a SOAP based web service in seconds - not so easy with REST. But help is on the way.

JSR 311: JAX-RS: The Java API for RESTful Web Services aims to simplify the process. Paul Sandoz, co-specification lead along with Marc Hadley, does a nice job of introducing JAX-RS in the presentation he delivered last month at Jazoon, specifically by comparing the work you'd have to do using just the servlet API versus the proposed JAX-RS annotations.

The Sun Web Developer Pack contains an early access implementation of JAX-RS along with a tutorial. The tutorial starts with your standard hello application, but it provides a working copy of the application rather than instructions how how to build it from scratch. That's where I come in...

Setting Things Up

  • Download and install NetBeans 6.0. If you don't already have GlassFish installed, grab the Standard and Full distribution which has it included.
  • Download and install the SWDP to GlassFish.

Creating the hello Application

  1. Start NetBeans 6.0 and create a new Web Application named hello.
  2. Expand GlassFish under the Libraries node to verify that the SWDP was properly installed. If so, you'll see restbeans-api.jar and restbeans-impl.jar:



    If you do not see the rest libraries, try removing and adding the GlassFish to NetBeans.

  3. Create a new Java class named Hello. Set the package name to anything you like. I used rest. Hello will be a "resource class" identifiable by a URI.

  4. To associate the resource with a URI we use a UriTemplate annotation as follows:

    @UriTemplate("/hello")
    public class Hello {

  5. Next, define a method to handle the request:

        public String sayHello() {
            return new String("Hello there.");
        }

  6. Then use an HttpMethod annotation to indicate which type of HTTP request it responds to: GET, POST, PUT or DELETE.

        @HttpMethod("GET")
        public String sayHello() {
            return new String("Hello there.");
        }

  7. Finally, use a ProduceMime annotation to specify what type should be returned to the client:

        @HttpMethod("GET")
        @ProduceMime("text/plain")
        public String sayHello() {
            return new String("Hello there.");
        }

Building the hello Application

Before we can deploy the application, we need to generate a class that will load our resource classes (hello in our case), into the application. JAX-RS ships with an annotation processor that will generate this class for us. And NetBeans 6.0 ships with the Ant tasks necessary to call the annotation processor. You'll find it in build-impl.xml. The only problem is these tasks will only run if REST support is turned on:



and NetBeans 6.0 does not yet include an option to turn on REST support via the project's properties, so we just have to do it manually.

  1. Alt+Shift+O to open private.properties and add the following:

    rest.support.on=true
  2. Press F11 to build the project and generate the class RESTBeansResources, which you'll find in the build/generated/rest-gen/restbeans folder under the Files tab:



There's one more piece to the runtime puzzle, and that's the servlet that kicks everything off, which is provided by the JAX-RS runtime: com.sun.ws.rest.impl.container.servlet.ServletAdaptor. If you look in the WEB-INF directory above, you see a web.xml, which loads this servlet, was also generated for us:

  <servlet>
    <servlet-name>RESTBeans Application</servlet-name>
    <servlet-class>
        com.sun.ws.rest.impl.container.servlet.ServletAdaptor
    </servlet-class>
    <init-param>
      <param-name>resourcebean</param-name>
      <param-value>restbeans.RESTBeansResources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>RESTBeans Application</servlet-name>
    <url-pattern>/restbean/*</url-pattern>
  </servlet-mapping>


However, the contents of this web.xml did not make it into our distributable.

  1. Ctrl+1 to switch to the Projects tab.
  2. Open web.xml under Configuration Files, switch to the XML view, and paste the code above just after the opening web-app tag.

Running the Application

  1. Open Project Properties and select the Run category. Set the Relative URL to /restbean/hello.
  2. Press F6 to run the application:



How It All Works

Much of how all of this works is explained in detail in the resources I list below. I found the RESTful Web Services tutorial and the Getting Started With RESTful Web Services Development articles particularly useful. However, in summary, we have an application flow which looks like the following:

ServletAdapter => RESTBeansResources => Hello

The ServletAdapter is provided by the JAX-RS runtime and loads the generated RESTBeansResources class, which in turn provides the REST resources - Hello in our application. The URL, /hello/restbean/hello, breaks down as follows:

/hello - the context root, configured in sun-web.xml
/restbean - mapped to the ServletAdapter, configured in web.xml
/hello - mapped to the Hello resource, configured using the @UriTemplate annotation in the Hello resource itself.

The Working Application

Admittedly, the application is very simple, but the real point of this post was to get you up and running with JAX-RS in NetBeans 6.0. It should now be possible to continue with the other exercises provided in the tutorial.

Resources


Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

  • I never understood the complaint.

    There's nothing that says that you have to play games with URLs to be a RESTful web service.

    I mean, this infrastructure is nice and all, but hardly required. The whole point of REST is that it uses (mostly) off the shelf URLs and payloads, that it leverages the HTTP protocol above and beyond GET and POST, and we've been dealing with those for years.

    The only thing that makes REST particularly "easy to use" is that you don't have to interoperate with any standard, that you don't have to ensure that your formats match some more formal spec, a spec that may well go beyond the needs of your application. You get to just "make it up", which keeps it very nimble and "agile".

    So, it's nice that it's now "easy to do", but, frankly, they weren't that hard before.

    Posted by: whartung on July 19, 2007 at 10:58 AM

  • Nice tutorial! I note that tweak on project.properties file is quite cumbersome, but fortunately it was just temporary. With the coming beta1 release of NB 6.0, the support would be turned on automatically as user typing in JSR-311 annotations. Even the setting up GlassFish installation for REST libary jars is not necessary anymore.

    Posted by: ntn on July 27, 2007 at 10:47 AM

  • I am having a problem configuring SWDP on Glasfish V2. I have installed Netbeans 6 M10. I am running Ubuntu. Netbeans and Glassfish were installed to default directories /usr/local and SWDP was installed in root folder. When I created Hello application, restbeans-api.jar and restbeans-impl.jar were not showing up under Glassfish directory structure. I tired removing and adding the GlassFish to NetBeans again but still I dont see those 2 files under Glassfish directory tree. Need Help. The tutorial by Arun Gupta said to Update Netbeans from Netbeans Update Center Beta. Dont know how thats possible in M10 incase that is required.

    Posted by: chirdeeptomar on July 28, 2007 at 08:32 AM

  • http://sports.yahoo.com/fantasy/nfl/news?slug=ab-rotoarcade_081307 read what he has to say about brian leonard the football player.

    Posted by: heyman4132 on August 13, 2007 at 11:32 PM

  • Too funny. Thanks for the pointer. /Brian

    Posted by: bleonard on August 14, 2007 at 05:15 AM

  • Loved the tutorial thanks a lot. I was wondering how to do the opposite of what you showed here. I am developing a REST web service in RoR and want to consume it from a Java Desktop application. Is there a tool in Netbeans or other IDE that generates the stub for the client side in a desktop application? Thank you for your time

    Posted by: gustavomartin on August 30, 2007 at 03:30 PM

  • chirdeeptomar: If you use netbeans 6.0 beta2 (http://bits.nbextras.org/netbeans/6.0/beta2/latest/), there is no need to install SWDP or Jersey library on GF. The support for REST on NB 6.0 grows at a quick pace. Please see: http://www.netbeans.org/kb/60/websvc/rest.html for latest info.

    Posted by: ntn on October 25, 2007 at 10:47 AM

  • First of all thanks for the well organized tutorial. I have tried to implement the same.But got stuck in the middle. After building the application, it says "Build Successful". When i tried to run the application following error has been displayed on the browser "HTTP Status 404 - Servlet RESTBeans Application is not available" When i observed the build folder, it has not generated the folders and classes related to the RESTBean resources even though the build was sucessful. Nore: rest.support.on=true property has been set in properties file. Plz reply if any body gets some info for the above problem. Thanks

    Posted by: srini925 on April 03, 2008 at 05:58 AM

  • UPDATE: Since this blog was written, the Jersey project has taken the place of the Sun Web Developer Pack. Jersey is the reference implementation of JAX-RS (JSR 311) and NetBeans has excellent support for Jersey. If you're using NetBeans 6.0, just go to Tools > Plugins and install the RESTful Web Services plugin. In NetBeans 6.1 this plugin is included with the standard distribution. So the steps I outline to start working with JAX-RS are no longer necessary - just get NetBeans and go. /Brian

    Posted by: bleonard on April 23, 2008 at 01:17 PM



Only logged in users may post comments. Login Here.


Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds