Close

Deploy your apps in the cloud today.

Go from concept to live in minutes.

GET STARTED FREE

Rapidly build a rich three-tier web app, Part 3: Create a rich web UI

Use Rational Application Developer to quickly build a multi-tier Java EE application and deploy it to IBM Bluemix

10 March 2015
PDF (943 KB)
Share:
author photo

Steve Arnold

Technical Consultant

 

This three-part tutorial walks you through building a multi-tier web application from scratch, using IBM® Rational® Application Developer for WebSphere Software, the Java Persistence API (JPA), Enterprise JavaBeans (EJBs), REST web services, and — for a rich Web 2.0 front end — the Dojo Toolkit. You'll end up with a fully functioning web application that displays data in a table that users can edit by double-clicking any cell.

In Part 1 you created a database on IBM Bluemix, connected to it from Rational Application Developer, and populated it with sample data. In Part 2, you created the application tier consisting of an EJB for managing the business logic and Java Persistence API (JPA) entities for interacting with the database. Here in Part 3 you'll expose the EJB methods as REST web services and build an editable Dojo data grid for viewing and modifying the data. Finally, you'll deploy the application to IBM Bluemix.

Create a new web project

 

Start by creating a new web project in Rational Application Developer:

  1. Right-click the CustomerEAR project and choose New > Web Project. Choose Dojo Toolkit as the template, and specify CustomerWeb as the Name: Screenshot of first page of New Web Project wizard
  2. Click Next.
  3. Click the Deployment tab. Ensure that the runtime is set to WebSphere Application Server V8.5 Liberty Profile and that the EAR file is CustomerEAR: Screenshot of deployment page of New Web Project wizard
  4. Click the Change Features... button. Select Context and Dependency Injection (CDI) and JAX-RS (REST Web Services): Screenshot of the project facets dialog box
    By adding these two facets, you enable your web project to have the reference to the EJB injected by the container, and you can define the web service through the use of annotations. Both facets make the programming of the application much simpler by reducing the amount of esoteric and complex code you need to write.
  5. Click OK.
  6. Back in the New Web Project dialog box, click Finish. If prompted to change perspective to the web perspective, click yes.

Create the REST-based web service

 
  1. In the Enterprise Explorer view, select the CustomerWeb project, right-click, and choose New > Class.
  2. Set the package to services and the name to CustomerService, and click Finish. The new class should open in the Java editor.
  3. In the Java editor, add these two lines immediately before the class declaration:
    @Path(value="/customerService")
    @Produces(MediaType.APPLICATION_JSON)

    These annotations define the class as a REST web service, specify its URL, and set the kind of output the methods will produce.
  4. Add the following lines of code inside the class declaration:
    @EJB
    private CustomerEJBLocal customerEJB;

    These lines declare a reference to the EJB and use annotations to request that the web container inject a reference to the EJB, so you don't need to look it up.
  5. Press Ctrl-Shift-O to add the imports. (Choose javax.ws.rs.core.MediaType and the javax.ws.rs.Produces.) An error still occurs because a compile-time reference to the EJB project is absent. Click the light-bulb icon and select fix project setup.... Choose the default option to Add CustomerEJB to the build path and click OK.
  6. Now you can create the two web services. Add the following code to your class:
    	@GET
    	@Produces(value=MediaType.APPLICATION_JSON)
    	public List<Customer> getCustomers() {
    	    return customerEJB.getCustomers();
    	}
    	 
    	@PUT
    	@Path(value="update/{id}/{name}/{address}/{country}")
    	publicvoid updateCustomer(@PathParam("id") String id,
    	    @PathParam("name") String name,
    	    @PathParam("address") String address,
    	    @PathParam("country") String country)  
    	{
    	    customerEJB.updateCustomer(id,name,address,country);
    	}

    The various annotations define whether the web service is a get, put, post, or delete; the path of the service; and a mapping to any parameters that are passed in. The actual code is simple and delegates straight through to the EJB; it could be used, though, for calling multiple EJBs or for manipulating the results in some way.
  7. Press Ctrl-Shift-O again to fix the imports (selecting java.util.List when prompted). The code should now look like this:
    package services;
    
    import java.util.List;
    
    import javax.ejb.EJB;
    import javax.ws.rs.GET;
    import javax.ws.rs.PUT;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import ejbs.view.CustomerEJBLocal;
    import entities.Customer;
    
    @Path(value="/customerService")
    @Produces(MediaType.APPLICATION_JSON)
    public class CustomerService {
    
    	@EJB
    	private CustomerEJBLocal customerEJB;
    
    	@GET
    	@Produces(value=MediaType.APPLICATION_JSON)
    	public List<Customer> getCustomers() {
    	    return customerEJB.getCustomers();
    	}
    		 
    	@PUT
    	@Path(value="update/{id}/{name}/{address}/{country}")
    	public void updateCustomer(@PathParam("id") String id,
    	    @PathParam("name") String name,
    	    @PathParam("address") String address,
    	    @PathParam("country") String country)  
    	{
    	    customerEJB.updateCustomer(id,name,address,country);
    	}

Declare the service

 

Before you can test the web service, you must declare the service so that the application server knows about it. This step involves creating a Java class that registers the service, and modifying the web configuration so that it knows about the registering Java class. You can make use of some of the quickfixes in Rational Application Developer to make this step a bit easier:

  1. In the Enterprise Explorer view, open CustomerWeb > WebContent > WEB_INF and open the web.xml file.
  2. Select the Servlet (JAX-RS Servlet), right-click, and choose Add > Initialization parameter. Don't fill in any of the details. Save the file.
  3. Open the Problems view (Windows > Show View > Problems) and find the JSR-311, 2.3.2 the param-name should be javax.ws.rs.Application warning. Right-click the light bulb and choose quickfix. When prompted, choose to create a new JAX-RS application.
  4. In the Java Class dialog box, set the package to services and set the name to CustomerWebApplication. Click Finish.
  5. In the Java editor for CustomerWebApplication, add the following code after the constructor that registers the service:
    @Override
    public Set<Class<?>> getClasses() {
       Set<Class<?>> classes = new HashSet<Class<?>>();
       classes.add(CustomerService.class);
       return classes;
    }
  6. Press Ctrl-Shift-O and save the file. The code should now look like this:
    package services;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import javax.ws.rs.core.Application;
    
    public class CustomerWebApplication extends Application {
    
    	public CustomerWebApplication() {
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public Set<Class<?>> getClasses() {
    		Set<Class<?>> classes = new HashSet<Class<?>>();
    		classes.add(CustomerService.class);
    		return classes;
    	}
    
    }

Start and test the service

 

The web service is now ready to be started and tested:

  1. Go to the Servers view, right-click WebSphere Application Server V8.5 Liberty profile at localhost, and choose Start. If necessary, republish (by right-clicking on the server and choosing Republish). The server should say that it is started and synchronized. If you are prompted to add JAX-RS features on the server, accept this choice, which saves you having to configure the server manually: Screenshot of Servers view showing started Liberty server
  2. Back in the Enterprise Explorer view, expand CustomerWeb, select Services > REST > customerService > getCustomers(), right-click, and choose showURI.
  3. Copy the URI (for example, http://localhost:9080/CustomerWeb/jaxrs/customerService) into a browser and confirm that you get a JSON-formatted list of customers from the database, similar to this: Screenshot of JSON results returned by the web service

You've now finished creating the web services, and you've also tested that the EJB and JPA code is successfully connecting to the database and retrieving data. Next you'll create the Dojo web application for viewing and modifying the data.

Create rich Dojo web page for using the services

 
  1. In the Enterprise Explorer view, select the CustomerWeb project, then right-click and choose New > Web Page. Specify Customers.html as the name and choose HTML as the basic template: Screenshot of new web page wizard
  2. Click Finish.
  3. Open the Customers.html web page. In the palette view (normally on the right side of the web perspective), open the Dojo Layout Widgets drawer and drag the BorderContainer onto the blank page. Select the Top and Center check boxes: Screenshot of Insert Border Container dialog box
  4. Click OK.
  5. Double-click the heading section and type All Customers.
  6. Switch to the Source view, where you'll add the data grid and populate it using the JSON results from the web service call.
  7. Find the <script> tags and replace them with the following code:
    <script type="text/javascript">
    require(
    // Set of module identifiers
    [ "dojo", "dojo/ready", "dijit/dijit", "dojo/parser",
    		"dijit/layout/BorderContainer", "dijit/layout/ContentPane",
    		"dojox/grid/DataGrid", "dijit/form/TextBox",
    		"dojo/data/ItemFileWriteStore" ],
    // Callback function, invoked on dependencies evaluation results
    function(ready) {
      dojo.ready(function() {
        console.log("in the ready function");
        dojo.xhrGet({
        url : "http://localhost:9080/CustomerWeb/jaxrs/customerService/",
        handleAs : "json",
        load : function(response) {
          console.log(response);
          var newData = {
            identifier : "custno",
            items : response
          };
          var dataStore = new dojo.data.ItemFileWriteStore({
            data : newData,
            id : "dataStoreId"
          });
          // set the layout structure:
          var customerLayout = [ {
            field : 'name',
            name : 'Name',
            width : '100px',
            editable : true
          }, {
            field : 'address',
            name : 'Address',
            width : '200px',
            editable : true
          }, {
            field : 'country',
            name : 'Country',
            width : 'auto',
            editable : true
          } ];
          var grid = new dojox.grid.DataGrid({
            id : "customerGrid",
            jsid : "customerGrid",
            store : dataStore,
            structure : customerLayout
          }, dojo.byId("customerGrid"));
          grid.startup();
          },
          error : function(response) {
          }
        });
      });
    });
    </script>

    The added code programmatically creates a table and populates it with the results from the web service call.
  8. In the script code, update the web service call with your URL.
  9. After the end-script marker and before the end of the header, add some links to the stylesheets for the grid so that the ending portion of the looks like this:
    </script>
    <link rel="stylesheet" type="text/css" title="Style"
    	href="dojo/dojox/grid/resources/Grid.css">
    <link rel="stylesheet" type="text/css" title="Style"
    	href="dojo/dojox/grid/resources/claroGrid.css">
    </head>
  10. Declare in the page where you want the grid to be positioned: In the main body of the page, find the central content pane, and inside that section, add a div section for the table:
    <div data-dojo-type="dijit.layout.ContentPane"data-dojo-props="region:'center'">
    	  <div id="customerGrid"></div>
    
    	</div>
  11. Make sure the server is running and synchronized. Then, in the Project Explorer, select Customers.html, right-click, and choose Run As > Run On Server.
  12. In the Run On Server dialog box, select the Liberty server and click Finish. You can then see the page containing the data grid start up in a browser: Screenshot of webpage with table

Persist changed values

 

In the browser page you can sort the grid by clicking a column header and edit the cell values by double-clicking. But the changed values aren't persisted to the database, so the final step for the UI setup is to call the update method on the EJB when a cell is changed:

  1. Switch back to the source view of the web page.
  2. Find the line of code that says grid.startup(); and add the following code directly after that line:
    grid.startup();
    grid.on("ApplyCellEdit", function(inValue, inRowIndex, inFieldIndex) {
      var rowData = grid.getItem(inRowIndex);
      var custNo = grid.store.getValue(rowData, "custno");
      var address = grid.store.getValue(rowData, "address");
      var name = grid.store.getValue(rowData, "name");
      var country = grid.store.getValue(rowData, "country");
      console.log("You modified row " + inRowIndex + "custNo is " + custNo);
      dojo.xhrPut({ url : " http://localhost:9080/CustomerWeb/jaxrs/customerService/update/" 
        + custNo + "/" + name + "/" + address + "/" + country,
        handleAs : "json",
        load : function(response) {
          console.log(response);
          },
          error : function(response) {
          }
          });
          console.log("After requesting the order code")
        }, true);

    The added code registers a cell edit handler, which calls the update method on the EJB.
  3. Modify the URL of the update operation if needed, and save the Customers.html web page.
  4. In the Enterprise Explorer, right-click the web page and choose Run As > Run on Server.
  5. After the web page is open, copy the URL to an external browser such as Firefox or Chrome. Try changing a cell value by double-clicking the cell, changing the value, and then pressing Enter or clicking outside of the cell.
  6. Refresh the web page to verify whether the value changed in the database.
  7. In the Data Source Explorer, select the CUSTOMER table, right-click, and choose Data > Return All Rows. You can now see your updated value in the database.

You've successfully built a multitier rich web application using JPA, EJB, web services and Dojo! All that's left is to deploy the application to IBM Bluemix, IBM's platform-as-a-service in the cloud.

Deploy the app to Bluemix

 

Now you'll set up Bluemix as an application server and deploy to it — exactly as you would deploy to any other application server.

Set up Bluemix as a server

 
  1. If you don't see the IBM Bluemix Runtime listed, ensure that you are running Rational Application Developer 9.1.1. Then go back to the Installation Manager and modify the installation to include the Bluemix Tools feature.

    In Rational Application Developer, go to Windows > Preferences and select Server > Runtime environments. Click Add.
  2. Under the IBM folder, select IBM Bluemix Runtime, and make sure that the Create a new local server check box is selected: Screenshot of the New Server Runtime wizard
  3. Click Next.
  4. In the IBM Bluemix Account window, specify your email address and Bluemix password. Click Validate Account, and then click Finish.
  5. Click OK to close the Preferences dialog box.
  6. Switch to the Web perspective and open the Servers view. You should now see IBM Bluemix listed as one of the servers.
  7. Update the web page to refer to the Bluemix web service instead of your local service: Choose a unique name for your app. Open customers.html, and replace each of the two instances of localhost:9080 with youruniqueappname.mybluemix.net.
  8. Save the file.

Deploy to Bluemix

 

You are now ready to deploy the application to Bluemix. The steps are exactly the same as for deploying any application from Rational Application Developer, but you'll be prompted for information about the Bluemix application name and any services your application requires. Under the covers the application is then pushed to Bluemix, bound to the services, staged, and started.

  1. In the Servers view, right-click the IBM Bluemix server and choose Add and Remove. In the Add and Remove dialog box, first remove the existing application. Then select CustomerEAR and click Add to add it to the Configured list: Screenshot of dialog box showing configured CustomerEAR
  2. Click Finish.
  3. Click Finish in the Delete Services dialog box. Do not select the SQLDB service — because the initial application you created is being removed, but you don't want to remove the database you've set up, which the deployed application will use.
  4. After a few seconds the project starts to deploy to Bluemix, and you're prompted to provide application details. In the Application details window, click Next.
  5. In the Launch deployment window, type the unique subdomain that you chose earlier into the Subdomain field: Screenshot of Launch Deployment wizard page
  6. Click Next.
  7. In the Services selection page, select the data service you created earlier that contains the application database.
  8. Click Finish.

Rational Application Developer now packages the application, pushes it to Bluemix, and binds it to the database. When the deployment finishes, you can access the application through http://yourdomain.mybluemix.net/CustomerWeb/customers/html, where you can see the data being returned in the table view and can edit the data by double-clicking any cell.

Conclusion

 

In this three-part tutorial, you rapidly built a Dojo/Jax-RS/JEE/JPA app in Rational Application Developer and deployed it directly to the Bluemix PaaS. Remember that you can easily scale the example application, using it as a model for more-complex multitier JEE applications.

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Rational, Cloud computing, Java technology
ArticleID=1000308
ArticleTitle=Rapidly build a rich three-tier web app, Part 3: Create a rich web UI
publish-date=03102015