Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

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

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

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

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

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

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

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

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

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

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

Figure 4.10 Greeting results

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020