The Java EE 6 Tutorial, Volume I

Example: Creating a Simple Hello World Application Using JAX-RS and Jersey

This section discusses the simple RESTful web service that is included with the tutorial examples in the directory jaxrs/JAXRSHelloWorld. This example was created by following the steps similar to those described in Creating a RESTful Web Service Using NetBeans IDE.

JAXRSHelloWorld Example: Discussion

With this simple application, a simple root resource for a RESTful web service was selected. This generates a RESTful root resource class with GET and PUT methods. This design is useful for creating examples such as this simple Hello World service.

In this example, the method getHtml() is annotated with @GET and the @Produces("text/html") annotation. This method will process HTTP GET requests and produce content in HTML. To finish this example, you simply need to replace the current contents of this example with a statement that returns Hello World. This example has also replaced the name of the method with the name sayHello. Here is the code for the completed sayHello() method:

@GET
    @Produces("text/html")
    public String sayHello() {
        return "Hello World";
    }

ProcedureTesting the JAXRSHelloWorld Example

  1. Open the project javaeetutorial/jaxrs/JAXRSHelloWorld in NetBeans IDE.

  2. Right-click the project node, JAXRSHelloWorld, and select Test RESTful Web Services.

  3. Click the helloWorld service in the left pane.

  4. The Get(text/html) method is selected by default. Click Test.

  5. The response Hello World, displays in the lower pane, as shown in the following figure.

    Figure 13–1 Testing JAXRSHelloWorld Web Service

    Browser displaying the result of testing the helloWorld
method, which is the words Hello World in a section of the window titled Response.

ProcedureDeploying and Running the JAXRSHelloWorld Example

Before You Begin

The application's Run properties must be set to run the RESTful web service. For the provided application, this task has been completed. For future reference, right-click the project node, select Properties, then select Run, and enter the Relative URL. For this example, you would enter /resources/helloWorld.

  1. Right-click the project node, JAXRSHelloWorld, and select Deploy.

  2. Right-click the project node, JAXRSHelloWorld, and select Run.

  3. A browser opens and displays Hello World at the URL http://localhost:8080/HelloWorld/resources/helloWorld.

    The browser displays the text “Hello World”.