The Java EE 6 Tutorial, Volume I

Creating a RESTful Web Service

This section discusses two ways that you can create a RESTful web service. If you choose to use NetBeans IDE to create a RESTful web service, the IDE generates a skeleton where you simply need to implement the appropriate methods. If you choose not to use an IDE, try using one of the example applications that ship with Jersey as a template to modify.

Procedure Creating a RESTful Web Service Using NetBeans IDE

This section describes, using a very simple example, how to create a Jersey-annotated web application from NetBeans IDE.

  1. In NetBeans IDE, create a simple web application. This example creates a very simple “Hello, World” web application.

    1. Open NetBeans IDE.

    2. Select File->New Project.

    3. From Categories, select Java Web. From Projects, select Web Application. Click Next.


      Note –

      For this step, you could also create a RESTful web service in a Maven web project by selecting Maven as the category and Maven Web Project as the project. The remaining steps would be the same.


    4. Enter a project name, HelloWorldApplication, click Next.

    5. Make sure the Server is Sun GlassFish v3 (or similar wording.)

    6. Click Finish. You may be prompted for your server Administrator User Name and Password. If so, enter this information.

  2. The project will be created. The file index.jsp will display in the Source pane.

  3. Right-click the project and select New, then select RESTful Web Services from Patterns.

    1. Select Simple Root Resource. Click Next.

    2. Enter a Resource Package name, like helloWorld.

    3. Enter helloworld in the Path field. Enter HelloWorld in the Class Name field. For MIME Type select text/html.

    4. Click Finish.

    5. The REST Resources Configuration page displays. Select OK.

      A new resource, HelloWorld.java, is added to the project and displays in the Source pane. This file provides a template for creating a RESTful web service.

  4. In HelloWorld.java, find the getHtml() method. Replace the //TODO comment and the exception with the following text, so that the finished product resembles the following method.


    Note –

    Because the MIME type that is produces is HTML, you can use HTML tags in your return statement.


    /**
         * Retrieves representation of an instance of helloWorld.HelloWorld
         * @return an instance of java.lang.String
         */
        @GET
        @Produces("text/html")
        public String getHtml() {
            return "<html><body><h1>Hello, World!!</body></h1></html>";
        }
    
        
  5. Test the web service. To do this, right-click the project node and click Test RESTful Web Services.

    This step will deploy the application and bring up a test client in the browser.

  6. When the test client displays, select the helloworld resource in the left pane, and click the Test button in the right pane.

    The words Hello, World!! will display in the Response window below.

  7. Deploy and Run the application.

    1. Set the Run Properties. To do this, right-click the project node, select Properties, and then select the Run category. Set the Relative URL to the location of the RESTful web service relative to the Context Path, which for this example is resources/helloworld.


      Tip –

      You can find the value for the Relative URL in the Test RESTful Web Services browser window. In the top of the right pane, after Resource, is the URL for the RESTful web service being tested. The part following the Context Path (http://localhost:8080/HelloWorldApp) is the Relative URL that needs to be entered here.

      If you don't set this property, by default the file index.jsp will display when the application is run. As this file also contains Hello World as its default value, you might not notice that your RESTful web service isn't running, so just be aware of this default and the need to set this property, or update index.jsp to provide a link to the RESTful web service.


    2. Right-click the project and select Deploy.

    3. Right-click the project and select Run.

      A browser window opens and displays the return value of Hello, World!!

See Also

For other sample applications that demonstrate deploying and running Jersey applications using NetBeans, read Example: Creating a Simple Hello World Application Using JAX-RS and Jersey and/or look at the tutorials on the NetBeans tutorial site, such as the one titled Getting Started with RESTful Web Services. This tutorial includes a section on creating a CRUD application from a database. Create, read, update and delete (CRUD) are the four basic functions of persistent storage and relational databases.

ProcedureCreating a RESTful Web Service From Examples

The easiest way to create and run an application without NetBeans IDE is to copy and edit one of the Jersey sample applications. These samples are installed into the as-install/jersey/samples directory when the Jersey Documentation and Samples are installed onto the Enterprise Server using the Update Tool. The process of installing from the Update Tool is described in Java EE 6 Tutorial Component. This task uses the simplest sample application, helloworld-webapp, to demonstrate one way you could go about creating your own application without NetBeans IDE.

Before You Begin

Before you can deploy the Jersey sample applications to GlassFish from the command line, you must have downloaded and installed Maven onto your system. You can install Maven from the Maven website at http://maven.apache.org.

  1. Copy the helloworld-webapp application to a new directory named helloworld2. You will find this application in the directory as-install/glassfish/jersey/samples/helloworld-webapp.

  2. Do a search for all directories named helloworld-webapp and rename them to helloworld2.

  3. Search again for all files containing the text helloworld-webapp and edit these files to replace this text with helloworld2.

  4. Using a text editor, open the file jersey/samples/helloworld2/src/main/java/com/sun/jersey/samples/helloworld/resources/HelloWorldResource.java.

  5. Modify the text that is returned by the resource to Hello World 2. Save and close the file.

  6. Use Maven to compile and deploy the application. For this sample application, it is deployed onto Grizzly. Enter the following command from the command line in the directory jersey/samples/helloworld2 to compile and deploy the application: mvn glassfish:run.

  7. Open a web browser, and enter the URL to which the application was deployed, which in this examples is http://localhost:8080/helloworld2/helloworld. Hello World 2 will display in the browser.

See Also

You can learn more about deploying and running Jersey applications by reviewing the many sample applications that ship with Jersey. There is a README.html file for each sample that describes the sample and describes how to deploy and test the sample, and there is a Project Object Model file, pom.xml, that is used by Maven to build the project. Find a project that is similar to one you are hoping to create and use it as a template to get you started.

An example that starts from scratch can be found here.

For questions regarding Jersey sample applications, visit the Jersey Community Wiki page, or send an email to the users mailing list, users@jersey.dev.java.net.

ProcedureCreating a RESTful Web Service From Maven Archetype

Although this tutorial does not present instructions on using Maven for creating applications as a general rule, because Project Jersey is built, assembled and installed using Maven, and all of its sample applications are Maven-based, this section provides an example that creates a skeleton Jersey application from a Maven archetype.

Before You Begin

This example requires that Maven be installed and configured to run from the command line on your system. Maven can be downloaded from http://maven.apache.org/.

  1. Start the Enterprise Server. For instructions on how to do this, read Starting and Stopping the Enterprise Server.

  2. After Maven is installed, run the following from the command line:

    mvn archetype:generate -DarchetypeCatalog=http://download.java.net/maven/2

    The archetype catalog will download. You will be prompted to select the type of archetype you want to create. As of the publication date of this tutorial, the following choices display in the command window. These options are likely to change, but are provided here to give you an idea of what they might look like.


    Choose archetype:
    1: http://download.java.net/maven/2/archetype-catalog.xml -> 
    jersey-quickstart-grizzly (Archetype for creating a RESTful web 
    application with Jersey and Grizzly)
    
    2: http://download.java.net/maven/2/archetype-catalog.xml -> 
    jersey-quickstart-webapp (Archetype for creating a Jersey based RESTful 
    web application with WAR packaging)
    
    3: http://download.java.net/maven/2/archetype-catalog.xml -> 
    jersey-quickstart-ejb (Archetype for creating a Jersey based RESTful EJB 
    application with WAR packaging)
    
    4: http://download.java.net/maven/2/archetype-catalog.xml -> 
    jsf2-simple-example-archetype (Simple JSF project with no non-JavaEE 
    dependencies)
  3. Select the appropriate option for the type of RESTful web service you would like to create.

    With the Grizzly-based archetype (selection 1), you will get a sample Java application, which you can run directly from Java without a need to deploy it to any container. The web application archetype (selection 2) enables you to build a WAR archive, which you could deploy onto any web Servlet container.

  4. Define a value for groupId, such as RESTHello.

  5. Define a value for artifactId, such as RESTHelloApp. This is the name of the web application as well as the directory in which the application is created.

  6. Define value for version: 1.0–SNAPSHOT. You can accept the default by not entering anything.

  7. Define value for package: groupId, such as restHello. This is the directory where the main Java files will be located, which is basedir/artifactId/src/main/java/package. If you used the example entries, this directory will be RESTHelloApp/src/main/java/restHello.

  8. Confirm properties configuration. Enter Y to confirm or N to cancel.

    Maven generates a new project containing a simple Hello World RESTful web service.

  9. Build and run your RESTful web service. First, change into the project directory, which is the artifactId, or RESTHelloApp if you used the example text.

    • For the Grizzly-based scenario (selection 1), build and run the web service on the Grizzy container using this command: mvn clean compile exec:java.

    • If you selected the WAR-based scenario (selection 2), build your WAR file using the command mvn clean package. Deploy the WAR file to your favorite Servlet container. To run it using the embedded version of GlassFish V3, use this command: mvn glassfish:run.

  10. Test the service in your browser.

    • Enter the following URL to run the Grizzly-based application (selection 1): http://localhost:9998/myresource. This is the location where it is published by default. The browser displays the text Got it!

    • Enter the following URL to run the WAR-based scenario (selection 2): http://localhost:8080/artifactId/webresources/myresource. If you used the example entries, enter http://localhost:8080/RESTHelloApp/webresources/myresource. This is the location where it is published by default. The browser displays the text Hi there!

      After starting the application using Grizzly, you should see output that looks similar to that in the example output, below:

      [INFO] ------------------------------------------------------------------------
      [INFO] Building RESTHelloApp
      [INFO]    task-segment: [clean, compile, exec:java]
      [INFO] ------------------------------------------------------------------------
      [INFO] [clean:clean]
      [INFO] [resources:resources]
      [INFO] Using default encoding to copy filtered resources.
      [INFO] [compiler:compile]
      [INFO] Compiling 2 source files to /export/home/japod/test/jaxrs-tutorial/
      			RESTHelloApp/target/classes
      [INFO] Preparing exec:java
      [INFO] No goals needed for project - skipping
      [INFO] [exec:java]
      Starting grizzly...
      Jersey app started with WADL available at http://localhost:9998/application.wadl
      Hit enter to stop it...

      After starting the application for the WAR-based scenario, you should see output that looks similar to that in the example output, below:

      [INFO] Building RESTHelloApp Jersey Webapp
      [INFO]    task-segment: [glassfish:run]
      [INFO] ------------------------------------------------------------------------
      [INFO] Preparing glassfish:run
      [INFO] [resources:resources]
      [INFO] Using default encoding to copy filtered resources.
      [INFO] snapshot org.glassfish:glassfish-parent:10.0-SNAPSHOT: checking for 
      			updates from 	glassfish-maven2-repository.dev.java.net
      [INFO] [compiler:compile]
      [INFO] Compiling 1 source file to /export/home/japod/test/jaxrs-tutorial/
      			RESTHelloApp/target/classes
      [INFO] [glassfish:run]
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: HK2 initialized in 479 ms
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.naming.impl.ServicesHookup@1342545 Init done in 486 ms
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.v3.server.Globals@6de609 Init done in 488 ms
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.v3.server.SystemTasks@e7e8eb Init done in 493 ms
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.v3.services.impl.HouseKeeper@1a6518 Init done in 503 ms
      Dec 8, 2009 1:20:34 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.v3.services.impl.CmdLineParamProcessor@8390b0 
      			Init done in 506 ms
      JMXMP connector server URL = service:jmx:jmxmp://localhost:8888
      Dec 8, 2009 1:20:35 AM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
      INFO: Listening on port 8080
      Dec 8, 2009 1:20:35 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: com.sun.enterprise.v3.services.impl.GrizzlyService@59cbda startup 
      			done in 815 ms
      Dec 8, 2009 1:20:35 AM com.sun.enterprise.v3.services.impl.
      			ApplicationLoaderService postConstruct
      INFO: loader service postConstruct started at 1260231635181
      Dec 8, 2009 1:20:35 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: Application Loader startup done in 883 ms
      Dec 8, 2009 1:20:35 AM com.sun.enterprise.v3.server.AppServerStartup run
      INFO: Glassfish v3 started in 883 ms
      Dec 8, 2009 1:20:38 AM com.sun.enterprise.web.WebModuleContextConfig 
      			authenticatorConfig
      SEVERE: webModuleContextConfig.missingRealm
      Dec 8, 2009 1:20:38 AM com.sun.jersey.api.core.PackagesResourceConfig init
      INFO: Scanning for root resource and provider classes in the packages:
        restHello
      Dec 8, 2009 1:20:38 AM com.sun.jersey.api.core.PackagesResourceConfig init
      INFO: Root resource classes found:
        class restHello.MyResource
      Dec 8, 2009 1:20:38 AM com.sun.jersey.api.core.PackagesResourceConfig init
      INFO: Provider classes found:
      Dec 8, 2009 1:20:38 AM com.sun.jersey.server.impl.application.
      			WebApplicationImpl initiate
      INFO: Initiating Jersey application, version 'Jersey: 1.1.4.1 11/24/2009 01:30 AM'
      Hit ENTER for redeploy