Introducing JAX-RS
Very soon after the REST model was described, it began to gain acceptance in the Java community. Early efforts focused on building REST services directly with Java Servlets, but an effort soon concentrated on creating a draft specification (JSR) for developing REST services in Java. The specification that resulted from that effort (JSR-033) became the JAX-RS standard. The authors of the JAX-RS standard set some specific goals for the JAX-RS approach:
- POJO based: The authors of the specification wanted to allow developers to build their services entirely with annotated POJOs—no special component model, such as earlier versions of EJB or web services standards, required.
- HTTP-centric: In keeping with the REST architectural approach, the JAX-RS standard assumes that HTTP is the only underlying network protocol. It does not attempt to be protocol independent—in fact, it provides simple mechanisms for exploiting the underlying HTTP protocol.
- Format independent: The developers of the standard also wanted to make the JAX-RS standard compatible with a number of different content types. Therefore, they focused on providing plugability so that additional content types could be added in a compliant way.
Basic Concepts: Resources and Applications
The most basic concept in the JAX-RS standard is the notion of a resource. A resource is a Java class that uses annotations to implement a RESTful service. If you consider a web resource to be a specific URI (or pattern of URIs) that represents an entity type, then the resource is the implementation of that entity. Resources are tied together logically by your Application subclass, which extends the javax.ws.rs.core.Application class provided by the JAX-RS runtime. To implement the simplest JAX-RS service in WebSphere Liberty profile, all you need are two classes and a bit of configuration.
A JAX-RS “Hello World” in WebSphere Liberty
Given that we need to introduce several concepts with JAX-RS, we assume that you’ll be developing your JAX-RS services inside Eclipse using the WebSphere Liberty Profile Test Server. For instructions on downloading and installing Eclipse, WebSphere Liberty, and the WebSphere Liberty tools for Eclipse, either see our website or take a look at Appendix A, “Installation Instructions.” Note that the following instructions were specifically written and tested on Eclipse Juno for Java EE Developers Service Release 2 and the WAS 8.5.5 Liberty Profile. If you’re using a different (later) version of Eclipse or WAS, you might see some differences, but they should remain nearly the same.
You start the process by creating a new Eclipse Dynamic Web Project. The JAX-RS specification gives container providers some flexibility in how they can implement the specification, but they assume that artifacts will be deployed in a Servlet container such as WebSphere Liberty. In the Eclipse web development tool suite, a web project represents artifacts that are meant to be deployed to a Servlet container and packaged in a WAR file. If you’re not familiar with development in Eclipse, you might want to first refer to any of the helpful tutorials on Java development with Eclipse.1
First, switch to a Java EE perspective in Eclipse. Then select File > New. The menu that pops up enables you to select a Dynamic Web Project. After you select that, the dialog box in Figure 4.1 appears.
Figure 4.1 Creating a new web project
Name your project RestServicesSamples. For this particular project, we want to walk you through all the pieces included in a web project using REST in Eclipse, so you won’t actually use all the built-in wizards for creating REST services that the Eclipse web tools provide. However, you will use some of the features to set up a project that uses JAX-RS and WebSphere Liberty.
Make sure that the Include in EAR check box is unchecked; you only need a WAR file from this project, so you don’t need to worry about inclusion in an EAR.
Next, click the Modify button. This takes you to the page in Figure 4.2, which enables you to add facets to your project. Facets enable you to specify requirements and dependencies on specific technologies—Eclipse automatically handles modifications such as classpaths after you declare that you need those facets. On this page, check the check boxes to include support for JAX-RS and JAXB in your project (we explain why you need JAXB in the later section “JAXB and More Interesting XML-Based Web Services”).
Figure 4.2 Modifying Facets
Finally, back on the Dynamic Web Project creation page, click Finish. Eclipse creates the project and might inform you through a dialog box that this type of project is best viewed in the JEE perspective; it asks if you want to open that perspective now. If you are not already in that perspective, answer Yes; you can work in the JEE perspective from then on.
Next, you need to create your first resource class. This resource class simply introduces you to many of the common annotations in JAX-RS and familiarizes you with the way you start and test REST services using Eclipse and the WebSphere Liberty Profile. Go to File > New > Class from within the web perspective, and open the dialog box in Figure 4.3 that enables you to create your first resource class.
Figure 4.3 Creating GreetingResource
Name your new class GreetingResource, and put it in a package named com.ibm.mwdbook.restexamples. Click Finish, and the Java Editor for your newly created class opens. At this point, you can go into the Java editor and change the newly created class stub to match the code in Listing 4.1.
Listing 4.1 GreetingResource
package com.ibm.mwdbook.restexamples; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/Greeting") public class GreetingResource { @GET public String getMessage() { return "Hello World"; } }
This little example doesn’t do much, but it does point out a few key aspects of resource classes in JAX-RS. First, notice that this class doesn’t descend from any specialized subclass, nor does it implement any special interfaces. This is in accordance with the design of the JAX-RS specification, which aimed to allow developers to implement services as annotated POJOs. This was a principle that originated in JEE5 and has continued into later specifications. Next, notice the @Path annotation at the class level. As with the other annotations, @Path corresponds to a particular class—in this case, javax.ws.rs.Path, which you must import. In fact, each of the annotations you import in this example come from the javax.ws.rs package. @Path determines where in the URI space this particular resource is placed. Adding a path of /Greeting states that the last part of the URL (the resource identifier) will end in /Greeting. Other parts of the URL can be in front of the path identifier, but at least this identifies the end. In terms of the JAX-RS specification, annotating a class like this makes it a root resource class. This distinction becomes important when we start discussing subresources later.
The final point to notice about this simple example is the @GET annotation. Remember that, in the REST model, the HTTP methods are the verbs of the service. If the URI represents the noun that the action is performed against, then the method is the action that is performed. So the meaning of this simple example is that you are GETting a greeting. That makes the response that we are returning, Hello World!, very appropriate! Now, of course, @GET isn’t the only HTTP method annotation you can use; in the later section “Handling Entity Parameters with POST and the Consumes Annotation,” we cover a case in which you use @POST, and Chapter 6 shows uses for @DELETE and @PUT as well.
The next piece of the puzzle to put in place is the Application subclass. According to the JAX-RS specification, the purpose of the Application subclass is to configure the resources and providers (we cover those later) of the JAX-RS application. In fact, you’ll be editing and adding to the Application subclass as we expand the examples. For now, we start with another File > New > Class and bring up the new class dialog box. Your Application subclass should be named BankingApplication and should be placed in the com.ibm.mwdbook.restexamples package. The class needs to inherit from javax.ws.rs.core.Application. Figure 4.4 shows the completed fields in the dialog box.
Figure 4.4 Creating the Application subclass
After you enter these fields, click Finish and then replace the template text of the newly created class with the text in Listing 4.2.
Listing 4.2 BankingApplication Class
package com.ibm.mwdbook.restexamples; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("/banking/*") public class BankingApplication extends Application { }
Note that we’ve added a single annotation in this class, the @ApplicationPath annotation. This annotation instructs the JAX-RS runtime what the path for JAX-RS resources will be. The path segment referenced in the annotation is added after the server name and web project context root, so resources are referenced by this pattern:
http://localhost:9090/RestServicesSamples/banking/your_resource_here
This is only one of three mechanisms defined in the Infocenter for configuring JAX-RS in the WebSphere Liberty Profile. This approach enables you to specify multiple JAX-RS applications with different application paths in the same JAR file, but it doesn’t allow you to set up security constraints for the applications. For information on how to set up JAX-RS to allow that, refer to the Infocenter.2
Creating the WebSphere Liberty Server
You’re almost ready to put the final piece in place for this simple example. Now that you’ve created all the artifacts necessary to implement a service, you need to deploy those artifacts into the WebSphere Liberty Profile. To do so, you must define a server in Eclipse. In this section, we assume that you created one server back in Chapter 2 when you tested a simple Web 1.0 example in Eclipse. If you haven’t done so, your panels might differ slightly. Remember the discussion in Chapter 2 on how you might have different servers for different layers in your application. One advantage of defining multiple servers is that it keeps your servers from being cluttered by association with projects you don’t need that might slow the startup of your particular server. For now, begin in the JEE Perspective by clicking the Servers tab at the bottom of the page, selecting the existing server you created in Chapter 2, and then using the right mouse button menu to select New > Server. The dialog box in Figure 4.5 then appears.
Figure 4.5 Define a New Server dialog box
In the Define a New Server dialog box, make sure you have selected WebSphere Application Server V8.5 Liberty Profile, and then click Next. The page in Figure 4.6 appears.
Figure 4.6 Creating a new server from an existing server
This dialog box informs you that you have already created one server named defaultServer and that this name is in use. On this page, click the New button. That action brings up the next page of this dialog box (see Figure 4.7).
Figure 4.7 New RESTServer creation
Give the server the name RESTServer. When you click Finish on the dialog box in Figure 4.7, you are taken back to the new Servers page, but this time you see a description of the server configuration for your new server, as in Figure 4.8. Note that your server is pretty bare bones at this time—only the basic configuration for your HTTP host and port is defined. That changes in the next step.
Figure 4.8 Add Project dialog box
The final task in creating your server is associating your project with the server you just created. Click the Next button one final time. The dialog box in Figure 4.8 enables you to associate your project with the server by clicking the Add button to move the project from the list of available projects on the left side over to the list of configured servers on the right side.
At this point, you can finally click the Finish button to finish configuring the server. This adds the required features (in this case, JAX-RS support) to the server.xml file. Feel free to examine the server.xml file to verify that it has been reconfigured.
Starting the Server and Testing the Application
You’re finally ready to test your application. Begin the process by starting the server you just created. On the Servers tab, click the green Start button in Figure 4.9.
Figure 4.9 Starting the server
Now switch to the Console tab and make sure you see a message stating something like the following:
[AUDIT ] CWWKZ0001I: Application SimpleBankingProject started in 0.419 seconds.
If you don’t see this message, or if see an error message instead, take a look through the earlier messages in the console to find out what you did wrong. You can also turn to the end of this chapter and look at the debugging hints for JAX-RS services. Finally, presuming that everything went well, you can open a browser and type the following into the URL line:
http://localhost:9080/RestServicesSamples/banking/Greeting
If everything worked correctly, you should see your REST service greeting you with Hello World! (see Figure 4.10).
Figure 4.10 Greeting results