Java J2EE Portal
Enterprise Java Station
J2EE curve
Java News / Articles
Java News / Articles
Debugging Java applications using IntelliJ IDEA
Groovy and Grails - A Getting Started Guide
spring Tutorial
Building Web Applications Using The Spring Framework
Processing...
Buy Java, Deals On Software Technology Store
Click here for great deals on computers, laptops, software and books
Creating a new Google Web Toolkit (GWT) application PDF Print
Written by Content Team   
Apr 02, 2007 at 02:04 AM

The random quote is selected from a list of quotes stored on the server. Every second our application will retrieve the random quote provided by the server, and display it on the web page in true AJAX style without refreshing the page.

1.Create a new Java file named RandomQuoteService.java in the com.packtpub.gwtbook.hellogwt.client package. Define a RandomQuoteService interface with one method to retrieve the quote:

public interface RandomQuoteService extends RemoteService
{
   public String getQuote();
}

2.Create a new Java file named RandomQuoteServiceAsync.java in the com.packtpub.gwtbook.hellogwt.client package. Define a RandomQuoteServiceAsync interface:

public interface RandomQuoteServiceAsync
{
   public void getQuote(AsyncCallback callback);
}

3.Create a new Java file named RandomQuoteServiceImpl.java in the com.packtpub.gwtbook.hellogwt.server package. Define a RandomQuoteServiceImpl class that extends RemoteService and implements the previously created RandomQuoteService interface. Add functionality to this class to return a random quote when the getQuote() method is called by a client.

public class RandomQuoteServiceImpl extends
                RemoteServiceServlet implements RandomQuoteService
{
private Random randomizer = new Random();
private static final long serialVersionUID=
                                -1502084255979334403L;
private static List quotes = new ArrayList();
static
{
	quotes.add("No great thing is created suddenly
	                                        -- Epictetus");
	quotes.add("Well done is better than well said
	                                        -- Ben Franklin");
	quotes.add("No wind favors he who has no destined port
	                                        --Montaigne");
	quotes.add("Sometimes even to live is an act of courage
	                                                -- Seneca");
	quotes.add("Know thyself -- Socrates");
}
public String getQuote()
        return (String) quotes.get(randomizer.nextInt(4));
}

That's all we have to do for implementing functionality on the server. Now, we will modify the client to access the functionality we added to the server.

4.Modify HelloGWT.java to remove the existing label and button and add a label for displaying the retrieved quote. Add functionality in the onModuleload() to create a timer that goes off every second, and invokes the RandomQuoteService to retrieve a quote and display it in the label created in the previous step.

       public void onModuleLoad()
       {
         final Label quoteText = new Label();
         //create the service
         final RandomQuoteServiceAsync quoteService =
                                 (RandomQuoteServiceAsync)GWT.create
                                         (RandomQuoteService.class);
         //Specify the URL at which our service implementation is
         //running.
         ServiceDefTarget endpoint = (ServiceDefTarget)quoteService;
         endpoint.setServiceEntryPoint("/");
         Timer timer = new Timer()
         {
           public void run()
           {
             //create an async callback to handle the result.
             AsyncCallback callback = new AsyncCallback()
             {
               public void onSuccess(Object result)
               {
                 //display the retrieved quote in the label
                 quoteText.setText((String) result);
               }
               public void onFailure(Throwable caught)
               {
                 //display the error text if we cant get quote
                 quoteText.setText("Failed to get a quote.");
               }
             };
             //Make the call.
             quoteService.getQuote(callback);
           }
         };
         //Schedule the timer to run once every second
         timer.scheduleRepeating(1000);
         RootPanel.get().add(quoteText);
       }

We now have the client application accessing the server to retrieve the quote.

5.Modify the HelloGWT.html to add a paragraph describing our AJAX application.

xe "application, GWT:generating, AJAX used" This is an AJAX application that retrieves a random quote from
the Random Quote service every second. The data is retrieved
and the quote updated without refreshing the page !

6.Let's make the label look nicer by adding a CSS for the label. Create a new file named HelloGWT.css in the com.packtpub.gwtbook.hellogwt.public package and add the following style class declaration to it:

       quoteLabel
       {
         color: white;
         display: block;
         width: 450px;
         padding: 2px 4px;
         text-decoration: none;
         text-align: center;
         font-family: Arial, Helvetica, sans-serif;
         font-weight: bold;
         border: 1px solid;
         border-color: black;
         background-color: #704968;
         text-decoration: none;
       }

7.Modify the label to use this style in the HelloGWT.java file:

quoteText.setStyleName("quoteLabel");

8.Add a reference to this stylesheet in the HelloGWT.html so the page can find the styles defined in the stylesheet.

xe "application, GWT:generating, AJAX used"

9.The last thing we have to do is register our RandomQuoteServiceImpl servlet class in the HelloGWT module so that the client can find it. Add the following line to HelloGWT.gwt.xml:

This servlet reference will be registered by the GWT framework with the
embedded Tomcat servlet container, so that when you run it in the hosted mode, the context path "/" is mapped so that all requests to it are served by the RandomQuoteServiceImpl servlet.


Here are the folders and files in the HelloGWT project after completing all the above modifications:

Our first AJAX application is now ready and we were able to create it entirely in Java without writing any HTML code!

What Just Happened?

The RandomQuoteService interface that we created is the client-side definition of our service. We also defined RandomQuoteServiceAsync, which is the client-side definition of the asynchronous version of our service. It provides a callback object that enables the asynchronous communication between the server and the client. The RandomQuoteServiceImpl is a servlet that implements this interface and provides the functionality for retrieving a random quote via RPC. We will look into creating services in detail in Chapter 3.

PAGE 4 OF 6



Add This Feed Button

Enter your Email


Java Expert Interviews
Ramesh Loganathan Pramati
Pramati 4.1 and beyond: An interview with Ramesh Loganathan
Satish Talim
Java and J2EE Today: An interview with Satish Talim
ChristopherDuncan
Programmers lose because they are unwilling to learn any skill beyond the technical
Processing...
Go to top of page  Home |
SiteMap

Copyright 2004 to 2008 Rightrix Solutions. All rights reserved. All product names are trademarks of their respective companies. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Rightrix Solutions and IndicThreads.com are independent of Sun Microsystems, Inc.

Views expressed at IndicThreads.com reflect the views of the authors alone, and do not necessarily reflect those of IndicThreads.com. IndicThreads.com and it's authors are not responsible for reader comments and opinions.

Enterprise Java J2EE JEE Portal >> IndicThreads.com