Getting Started with RESTful Web Services

REpresentational State Transfer (REST) is an architectural style for distributed hypermedia systems, such as the World Wide Web. Central to the RESTful architecture is the concept of resources identified by universal resource identifiers (URIs). These resources can be manipulated using a standard interface, such as HTTP, and information is exchanged using representations of these resources. In this tutorial, you first learn a bit about REST and then you are shown how NetBeans IDE supports this architectural style.


Content on this page applies to NetBeans IDE 7.1

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE Java EE download bundle
Java Development Kit (JDK) version 6 or 7
Java EE-compliant application server

Oracle WebLogic Server 11g-12c,
or GlassFish Server Open Source Edition 3.x.
(Does not work on Tomcat unless EJB support plugin is installed to Tomcat)

The jdbc/sample database on
Java DB (Derby) database server or MySQL
database server

On Java DB (Derby), The jdbc/sample database is generated by NetBeans IDE
when you install the IDE with the GlassFish application server.

On MySQL, the IDE populates the sample database after you create it on the MySQL server from within the IDE.

The GlassFish server can be installed with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit the the GlassFish server downloads page.

Important: Java EE 6 projects require GlassFish Server 3.x or Oracle WebLogic Server 12c.


RESTful web services are services built using the RESTful architectural style. Building web services using the RESTful approach is emerging as a popular alternative to using SOAP-based technologies for deploying services on the internet, due to its lightweight nature and the ability to transmit data directly over HTTP.

The IDE supports rapid development of RESTful web services using JSR 311 - Java API for RESTful Web Services (JAX-RS) and Jersey, the reference implementation for JAX-RS.

For detailed information, refer to the following:

In addition to building RESTful web services, the IDE also supports testing, building client applications that access RESTful web services, and generating code for invoking web services (both RESTful and SOAP-based.)

Here is the list of RESTful features provided by the IDE:

  1. Rapid creation of RESTful web services from JPA entity classes and patterns.
  2. Rapid code generation for invoking web services such as Google Map, Yahoo News Search, and StrikeIron web services by drag-and-dropping components from the Web Services manager in the Services window.
  3. Generation of RESTful Java Clients for services registered in the Web Services manager.
  4. Test client generation for testing RESTful web services.
  5. Logical view for easy navigation of RESTful web service implementation classes in your project.
  6. Fully integrated Spring framework, providing Spring transaction handling.

In this tutorial, you will be shown how the IDE supports you in generating, implementing, and testing RESTful web services.

RESTful Web Services, Persistence, and Entity Classes

RESTful web services in Java rely on the Java Persistence API to communicate with a database. Specifically, RESTful web services rely on entity classes and a persistence unit, as defined in the Persistence API. Entity classes are Java classes that map to objects in a relational database. According to The Java EE5 Tutorial, "An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table." A persistence unit consists of the set of entity classes, the data source, the persistence provider, and the persistence unit's own name, as defined in a persistence.xml file.

You can use NetBeans IDE either to create entity classes and RESTful web services in the same process, or you can use the IDE to create RESTful web services from existing entity classes. In this tutorial, you use the RESTful Services from Database wizard to generate entity classes and RESTful web services in the same process. The wizard automatically generates the persistence unit.

Using a MySQL Database Server

If you use the MySQL database server instead of JavaDB (Derby), you need to register the database server with the IDE and add the sample database to the server.

To use a MySQL database server with this tutorial:

  1. Register your MySQL server in the IDE, if the server is not registered. To register a MySQL server, go to the IDE's Services window, right-click the Databases node, and select Register MySQL server.
    Register MySQL Server option in Services window
  2. A dialog opens in which you type the configuration details of your MySQL server, including administrator user name and password. See "Configuring MySQL Server Properties" in Connecting to a MySQL Database.

    Basic properties of the MySQL server you are registering in the IDE
  3. Start the MySQL server and connect to it. See "Starting the MySQL Server" in Connecting to a MySQL Database.
  4. Right-click the MySQL server node and select Create Database. The Create MySQL Database dialog opens.
    Create Database context menu option
  5. Type sample as the new database name. Grant full access to your root user, or a user of your choice.
    New Database Name dialog filled out
  6. Click OK. A dialog opens informing you that sample is the name of a sample database, and asking you if you want to create the tables, objects, and data for this database.
    Prompt to populate database with sample data
  7. Click Yes. The IDE creates and populates the database, and adds a connection to the database.
    Generated sample database and database connection in Services window

Creating RESTful Web Services from a Database

The goal of this exercise is to create a project and generate entity classes and RESTful web services from a database.

This section uses the JavaDB (Derby) database and the jdbc/sample data source. JavaDB is included with the SDK. The jdbc/sample data source is generated by NetBeans IDE automatically when you install the IDE together with GlassFish.

Creating the Project

To create RESTful web services, you need a Java Web application project.

To create the project:

  1. Choose File > New Project (Ctrl-Shift-N on Linux and Windows, ⌘-Shift-N on MacOS). Under Categories, select Java Web. Under Projects, select Web Application. Click Next. The New Web Application wizard opens.

    Alternatively, you can create a Maven Web Application. Choose File > New Project (Ctrl-Shift-N on Linux and Windows, ⌘-Shift-N on MacOS). Under Categories, select Maven. Under Projects, select Maven Web Application and click Next.

  2. Under Project Name, enter CustomerDB. Click Next.
  3. Select either EE 6 or EE 5. Under Server, select the server you want to use, but note that EE 6 projects require GlassFish server 3 or later. Click through the remaining options and click Finish.

    Important for Maven Projects: You cannot set the server when you create a Maven web application. However, you have to set the server before you can create a persistence unit. Therefore, after you create the Maven web application, open the project's Properties and set the server in the Run properties. To open the project's Properties, right-click on the Project node and select Properties from the context menu.

Generating Entity Classes and RESTful Services

When you have a Java web application, add entity classes and RESTful web services to the project.

To generate entity classes and RESTful web services:

  1. Right-click the CustomerDB node and choose New > Other > Web Services > RESTful Web Services from Database. The New RESTful Web Service wizard opens, on the Database Tables panel.
    RESTful Web Services from Database option in menu
  2. In the Database Tables panel, if you are using the GlassFish server, select the jdbc/sample data source from the Data Source drop-down field.

    If you are using Tomcat, select jdbc:derby://localhost:1527/sample. If the Derby database server does not start automatically, you need to start it from the Databases tab in the Services window.

    Note for MySQL users: You have to create a new data source. Select New Data Source, give it an arbitrary descriptive name, and select the jdbc:mysql://localhost:3306/sample database connection. You created this connection when you created the sample database on MySQL.
    New data source using mysql connection

  3. Under Available Tables, select CUSTOMER and then click Add. The DISCOUNT_CODE table, which has a relationship with the CUSTOMER table, is also automatically added to the Selected Tables list. If you are using a MySQL database, the MICRO_MARKET table is also added. You now see the following (Derby version):

    Database Tables panel of New Entity Classes from Database wizard, showing CUSTOMER and DISCOUNT_CODE tables selected
  4. Click Next. The Entity Classes page opens. Under Package, type entities. You now see the following (Derby version).

    Note: The RESTful Web Services from Database wizard automatically generates JAXB annotations. If you generate entity classes for an EE6 application with the Entity Classes from Database wizard, and you might later want to create RESTful web services from those entity classes, make sure the Generate JAXB Annotations box is checked. You can also add JAXB annotations by hand to entity classes before running the RESTful Web Services from Entity Classes wizard. For more information, see NetBeans to Generate Simpler RESTful Web Services.

    Entity Classes panel of RESTful Web Services from Database wizard, showing package name
  5. Click Next. The Generated Classes panel opens. In this panel you can set the location of the RESTful web service classes that the IDE generates for your project. The Generated Classes panel differs between EE5 and EE6 RESTful web services, because EE5 projects include JPA controller classes but EE6 web services generate service classes as stateless session beans, instead.
    Generated classes page for EE5 project


  6. Accept the default packages and locations and click Finish. The IDE generates entity classes. Then a dialog opens, asking how you want to register RESTful resources. For EE5 projects, you have the (default) choice of using a Jersey RESTful servlet adaptor in the web.xml deployment descriptor, or of hand coding your own solution. For EE6 projects, you have the additional choice (default) of using a subclass of

    Spring framework applications: Register the RESTful resources in the web.xml deployment descriptor. Do NOT use

    Options for registering RESTful resources, EE6 application

The IDE now generates the RESTful web services. When the IDE is finished, look in the Projects window. The generated entity classes are in the entities package. Services are in the service package. For an EE5 project, there are JPA controller classes in the controller package and a web.xml deployment descriptor under Configuration Files.

Caution: The IDE might prompt you to Resolve Reference Problems for the project. In this case, right-click the CustomerDB project node and select Resolve Reference Problems. This issue can happen when the service is the first Jersey application to run on a WebLogic installation. In this case, the IDE solves the reference problem by copying the Jersey libraries to the server.

Complete EE5 RESTful service from database project

EE6 RESTful web services from a database instantiate EntityManager in each service class. This removes the need for JPA controller classes and generates simpler code.

Complete EE6 RESTful service from database project

Testing the RESTful Web Services

The goal of this exercise is to try out your application.

  1. Right-click the project node and choose Test RESTful Web Services. A dialog opens asking if you want to generate the test client inside the service project or in another Java web project. This option lets you work around security restrictions in some browsers. You can use any Web project, as long as it is configured to deploy in the same server domain as the CustomerDB project.
    Dialog for selecting whether to generate a test client locally or in another Java Web project deployed to the same domain
  2. Select where to generate the test client and click OK. The server starts and the application is deployed. When deployment is complete, the browser displays your application, with a link for each of the web services.

    If the output window shows an error message that one or more classes fails to exist and the project does not build, add the Jersey libraries to the compile-time libraries. Right-click the project node and select Properties. In the Properties tree menu, select Libraries. Click Add Library and browse for the Jersey libraries.

    RESTful web service tester landing page in browser

    On the left-hand side is the set of root resources. Here they are named entities.customer and entities.discountCodes.

  3. Click the entities.customer node. In the "Choose method to test" field, select either GET (application/json) or GET (application/xml). Click Test. The test client sends a request and displays the result in the Test Output section. The test client dispays the Raw View by default. The following image shows the response to an application/xml request.
    Raw view window in RESTful web service tester

There are 5 tabs in the Test Output section.

  • The Tabular View is a flattened view that displays all the URIs in the resulting document. Currently this view only displays a warning that Container-Containee relationships are not allowed.
  • The Raw View displays the actual data returned. Depending on which mime type you selected (application/xml or application/json), the data displayed will be in either XML or JSON format, respectively.
  • The Sub Resource tab shows the URLs of the root resource and sub resources. When the RESTful web service is based on database entity classes, the root resource represents the database table, and the sub resources represent the columns.
  • The Headers tab displays the HTTP header information.
  • The HTTP Monitor tab displays the actual HTTP requests and responses sent and received.

Exit the browser and return to the IDE.

Adding a Google Map Feature

The goal of this exercise is to add Google map functionality to our RESTful web services.

  1. Open the CustomerRESTFacade class (EE 5) or CustomerFacadeREST class (EE 6) in the editor.
  2. Add the following method to the class:
    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
       return "";
  3. Sign up for a Google map key at The Google map key request dialog has a field for your website's URL. Type http://localhost:8080 in that field.
  4. In the IDE, open the Services tab and expand the Web Services node. Under Web Services, expand Google. Under Google, expand Map Service.

    services view showing google map service
  5. Drag the getGoogleMap item and drop it into the body of the getGoogleMap method you created in Step 2, just before the return = ""; line. The Customize getGoogleMap SAAS dialog opens. Accept the defaults and click OK.

    The IDE adds the following try block to the getGoogleMap method.

    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
        try {
             String address = "16 Network Circle, Menlo Park";
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             //TODO - Uncomment the print Statement below to print result.
             //System.out.println("The SaasService returned: "+result.getDataAsString());
        } catch (Exception ex) {
        return "";

    The IDE also creates the packages org.netbeans.saas and, which contain the following classes and resources:

    • RestConnection - A wrapper around HttpUrlConnection
    • RestResponse - A wrapper for the HTTP response
    • - A properties file that stores the API key
    • GoogleMapService - A service wrapper containing the wrapper methods that uses RestConnection to make calls to the Google Map service.
    Projects window showing packages added after get Google Map method is dropped into Customer Resource
  6. In the try block of getGoogleMap(), replace the commented-out print statement with the line return result.getDataAsString();. The method now looks like this:
    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
        try {
             String address = "16 Network Circle, Menlo Park";
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             return result.getDataAsString();
        } catch (Exception ex) {
        return "";
  7. Open Paste in the API key you got from Google in Step 3. Save your changes. The IDE automatically redeploys your project.
  8. Refresh your browser window with the test client.
  9. Click entities.customer in the left sidebar. The GET (text/html) method appears in the "Choose method to test" field. Click Test. The GoogleMap of 16 Network Circle, Menlo Park opens in the Raw View.
    RESTful services test page showing Google map of Menlo Park
  10. The Google map of the Menlo Park address appears for all customers in the database. To display the Google maps of the actual addresses of the customers, create an instance of Customer and set the address equal to a concatenation of address variables for that instance of Customer.

    Find an instance of Customer by calling the entity manager's find() method. In an EE5 service, the customer facade uses its own find method to call CustomerJpaController, which instantiates the entity manager. In an EE6 service, the customer facade uses the abstract facade to access the entity manager. The generic find() method requires explicit argument type casting to Object and an explicit entity id. The following code displays the map location of the customer with id number 1 (changes in bold):

    EE5 service:

    public String getGoogleMap() {
        try {
             Customer c = find(1);
             String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
                     c.getCity() + " " + c.getState() + " " + c.getZip();
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             return result.getDataAsString();
         } catch (Exception ex) {
         return "";

    EE6 service:

    public String getGoogleMap() {
        try {
             Customer c = getEntityManager().find(Customer.class, 1);
             String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
                     c.getCity() + " " + c.getState() + " " + c.getZip();
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             return result.getDataAsString();
         } catch (Exception ex) {
         return "";
  11. Test the RESTful web services again. The customer id is specified as an argument for the find() method and the tester displays the raw view by default. For customer 1, the following map displays:

    Tip: Try to change the id number passed as an argument to getEntityManager().find(Customer.class, id). A real world client would get the value of this argument from a UI form.

    Google Map showing address of customer in database

    Note: If GoogleMaps cannot find an address, it shows a zoomed in view of the ocean.

RESTful Web Services in the Spring Framework

Jersey is integrated into the Spring Framework. When you create a Java Web application with the Spring framework, a REST-aware servlet is automatically created. However, Spring 3 doesn't contain aopalliance.jar, which the RESTful web service requires to inject an EntityManager object.

Creating a Java Web Application With the Spring Framework

When you create the Java Web application in the New Project wizard as described in Generating Entity Classes from a Database, after you select the server, click Next instead of Finish. This opens the Frameworks panel. Select Spring Web MVC, then click Finish.

Selecting the Spring framework when creating a Java web application

Adding aopalliance.jar to the Project

Spring 3 does not contain aopalliance.jar. The application requires this library to inject EntityManager. To fix the problem you need to download this jar and add it to your classpath. See Issue 193626 and the Spring forums.

To add aopalliance.jar:

  1. Download a zip archive of aopalliance.jar from
  2. Unzip the archive to the location of your choice.
  3. In the IDE's Projects window, right-click your Spring RESTful Web Service project node. The context menu opens.
    Context menu showing properties node
  4. Select Properties. The Properties dialog opens.
  5. In the Categories pane, select Libraries. Click Add JAR/Folder. A file system browser opens.
  6. Browse for aopalliance.jar. Use the absolute path reference. Click Open.
    Browsing for aopalliance.jar
  7. The aopalliance.jar file is now included in your libraries. Click OK.
    Library properties showing added aopalliance.jar

Creating RESTful Services in the Spring-enabled Project

After you create a Java web application with the Spring framework and add aopalliance.jar to the project's classpath, run the RESTful Web Service from Database wizard as described in Generating Entities and Services. However, do NOT register RESTful resources with a subclass of Instead use the web.xml deployment descriptor. The Spring framework generates a web.xml deployment descriptor in all cases.

Options for registering RESTful resources, web.xml chosen

For more about the features of Spring framework projects in NetBeans IDE, see Introduction to the Spring Framework.

Compilation Errors

You might have compilation errors in the generated service classes. You see these errors if you create the RESTful services before you add aopalliance.jar to the classpath.

To fix compilation errors in service classes:

  1. Make certain that you add aopalliance.jar to the classpath, as described in Adding aopalliance.jar to the Project.
  2. In the IDE's top menu bar, click Edit and select Find in Projects...
  3. Search for all occurrences of the @Error annotation in the project.
    Find in Projects dialog showing search for the @Error annotation
  4. Delete every @Error line from the code.
    Search results for @Error, with one line highlighted and about to be deleted

See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:

To send comments and suggestions, get support, and keep informed about the latest developments on the NetBeans IDE Java EE development features, join the mailing list.

get support for the NetBeans