Use Google Web Toolkit to develop Ajax

Source: Internet
Author: User

Ajax is a very popular web application development technology and an important part of Web 2.0. However, if you use the traditional JavaScript method for Ajax development, it will make the application very difficult to debug, thus reducing the production efficiency. Google's recently released GWT is expected to solve this problem for us. GWT is a framework for developing Ajax applications. It enables programmers to develop client and server code simultaneously using Java. The GWT compiler converts the Java code used for developing the client into JavaScript and HTML, and the programmer does not need to care about this conversion process. In this way, programmers can develop their own Ajax applications in their favorite Java IDE.

This article mainly introduces the following aspects:

1. Introduction to GWT features

2. Use GWT for UI development

3. Introduction to AJAX application development with JavaScript

4. Use GWT for Ajax Development

GWT features

1. Dynamic and reusable UI Components

The component library provided by GWT enables users to easily develop beautiful UIS. Each component corresponds to a class of GWT. In the second part of this article, we will introduce in detail how GWT supports the UI.

2. Simple RPC call

With GWT, you can easily implement communication between the client and the server, especially making asynchronous communication quite simple. The later part of this article will introduce in detail the RPC call using GWT.

3. More convenient debugging

Because HTML section is not generated during the development phase, the code developed by the user is actually run on the JVM, so that the user can debug the program using the traditional Java code debugging method, this speeds up debugging and reduces the time required for software development.

4. browser compatibility

In most cases, programs developed with GWT support IE, Firefox, Mozilla, Safari, and opera. users do not have to worry about browser compatibility during development. The compatibility of browsers is another tricky problem for programmers who use JavaScript For Ajax application development.

5. scalability

If you think the APIS provided by GWT cannot meet your needs, you can use jsni to directly embed Javascript statements into Java code.

Use GWT for UI development

In this section, we will discuss the support of GWT for UI development. GWT contains most of the components required for web development, such as buttons and text boxes. Figure 1 shows some UI components supported by GWT. From the image display effect, GWT can be used to make a very beautiful UI.

Figure 1: Some UI components supported by GWT

It is worth mentioning that each UI component must be placed in a control called panel. The Panel has different styles, which also determines the UI style. Figure 2 shows some panels supported by GWT.

Figure 2: Some panels supported by GWT

After reading these components, we will use an experiment to describe how to add the UI components to the page. The final result of this experiment is a logon window.

Before starting our experiment, we need to prepare the GWT environment. First, we need to download a Windows Version GWT on the Google website. The current version is 1.0.21. Then we need to configure the JDK environment on the machine. There are a lot of documents on the network for specific configuration methods, so we will not detail them here. Because this experiment is carried out in the eclipse development environment, you also need an eclipse environment. You can download the eclipse development environment from the eclipse official website. Next, we will introduce the experiment process in detail.

1. Create an Eclipse project

We can use projectcreator. cmd, a batch processing file that comes with GWT, to create an Eclipse project. As shown in figure 3, a project named myproject is created and stored under the myproject subdirectory of the current directory. for detailed usage of CMD, see Google's help documentation on GWT.

Figure 3: Use GWT to create an Eclipse project

2. Create a GWT Application

After creating the Eclipse project myproject, we use another batch processing file applicationcreator. CMD that comes with GWT to create a GWT application. Figure 4 shows the process of creating a GWT application. We have noticed that this batch processing file accepts a parameter named-Eclipse, which specifies an Eclipse project. In our example, it is specified as the Eclipse project myproject we just created.

Figure 4: Create a GWT Application

3. Import the Eclipse project

After creating the Eclipse project and the GWT application framework, we then import the Eclipse project to the eclipse development environment for further development. The specific import process is not described in detail. The imported project structure is shown in Figure 5.

Figure 5: import the Eclipse project

6. Add the UI component

After importing the project, we will find a Java file named democlient in the project. This file is created when you run the applicationcreator. CMD batch file. Now we need to add the required UI components to this Java file. We have added five components to this file: two labels, one button, one Textbox, and one passwordtextbox. The code list Listing 1 lists all the code of this program.

Listing 1: Sample GWT Application

1    package com.sample.myProject.client;2    import com.google.gwt.core.client.EntryPoint;3    import com.google.gwt.user.client.ui.Button;4    import com.google.gwt.user.client.ui.HorizontalPanel;5    import com.google.gwt.user.client.ui.Label;6    import com.google.gwt.user.client.ui.PasswordTextBox;7    import com.google.gwt.user.client.ui.RootPanel;8    import com.google.gwt.user.client.ui.TextBox;/** * This class is used to demostrate how to add widget onto the Web page */9    public class DemoClient implements EntryPoint {  /**   * This is the entry point method, when the module is load, this method   * will be automatically invoked.   */10  public void onModuleLoad() {11    Label labelName = new Label();12    Label labelPassword = new Label();    13    TextBox tbName = new TextBox();14PasswordTextBox tbPassword = new PasswordTextBox();15Button button = new Button();16    17    labelName.setText("Name:        ");18    labelPassword.setText("Password: ");19    button.setText("submit");20    21    HorizontalPanel hPanel = new HorizontalPanel();22    HorizontalPanel hPanel2 = new HorizontalPanel();23    24    hPanel.add(labelName);25    hPanel.add(tbName);26    hPanel2.add(labelPassword);27    hPanel2.add(tbPassword);    28    RootPanel.get().add(hPanel);29    RootPanel.get().add(hPanel2);30    RootPanel.get().add(button);31  }32   }

Next, let's analyze the program code and note that the class democlient inherits from entrypoint. All the classes that need to be eventually translated into HTML pages must inherit from entrypoint, And the onmoduleload method must be rewritten, this method is automatically called when the module is loaded. Therefore, we need to put the code for adding components into this function.

Five component instances are created in lines 11 to 15 of the program. There are two labels, one button, one textbox and one passwordtextbox respectively. Then, two label components and the display content of a button component are set in lines 17 to 19 of the program. The program's 21 rows and 22 rows wear two panel objects, both of which are horizontal panel objects. That is to say, the components placed in the panel are arranged horizontally. Lines 24 to 27 of the program Add the textbox and label components to the two panel objects respectively. At the end of the program, add the two panel objects and a button object created just now to the outermost panel.

7. Compile the application

After the code development is complete, we can double-click the DemoClient-compile.cmd batch file in the project to compile the Java file we developed into JavaScript and HTML. The compiled files are stored in the WWW subdirectory under the root directory of the project.

8. Run the program

After compiling the program, we will find that an HTML file named democlient.html is generated. Double-click the file, and the program runs as follows:

Figure 6: program running result

In this section, we mainly discuss how to add the UI components to the web page, and how these components interact asynchronously with the remote server will be discussed in the following sections.

Use JavaScript to develop Ajax applications

To enable users to better understand the differences between using GWT to develop Ajax applications and using traditional JavaScript to develop Ajax applications, this section briefly introduces how to use JavaScript objects to develop Ajax applications.

We all know that a core object in Ajax technology is the XMLHTTPRequest object, which supports asynchronous requests. The so-called asynchronous request is that when the client sends a request to the server, the client does not have to wait until the server responds. In this way, the whole page will not be refreshed, providing a better user experience. When the server returns a response, the client uses a JavaScript function to process the returned value to update the values of some elements on the page.

Because the methods for claiming XMLHttpRequest objects on IE and other browsers are different, we must distinguish different browsers when creating XMLHttpRequest objects using JavaScript. The method for creating an XMLHTTPRequest object is shown in the code in Listing 2.

Listing 2: Creating an XMLHTTPRequest object

1    function createObject(){2     try {3  xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");4  } catch (e1) {5  try {6    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");7  } catch (e2) {8    xmlHttpRequest = false;9  }10  }11  if (!xmlHttpRequest) {12 xmlHttpRequest = new XMLHttpRequest();13  }14  return xmlHttpRequest;      16  }

After creating the XMLHTTPRequest object, let's take a look at how to perform Asynchronous interaction with the server. Listing 3 lists the code that interacts with the server segment.

Listing 3: interacting with the server

1    function ajaxSample() {2        var xmlHttpRequest = createObject();3        var url = "/sampleServlet?userName=Jason";4        xmlHttpRequest.open("GET", url, true);5        xmlHttpRequest.onreadystatechange = updatePage;6        xmlHttpRequest.send(null);7    }

This Code demonstrates how to interact with the server. The first line of the program gets an XMLHTTPRequest object. The third line of the Program specifies the address of the server to respond to the client request. Line 2 of the program uses the XMLHTTPRequest object to open a connection. The first parameter specifies to pass the parameter through the get method, and the second parameter specifies the URL for receiving the request. In our example, it is a servlet, setting the last parameter to true means that the request to be sent is an asynchronous request. The 5th line of the Program specifies the callback function, that is, the JavaScript function executed after the server returns the result.

This section briefly introduces how to use JavaScript For Ajax development. Next we will detail how to use GWT for Ajax application development.

Ajax development with GWT

In the second part of the article, we have learned how to use GWT to create a project and add a GWT application to the project. Similarly, we also need to create a GWT project, add a GWT application. Because the default GWT program does not contain the sample code of the server, we must add it manually. The created Project gwtsample 7 is shown in. The main function of the instance we will introduce is to retrieve a string from the server through asynchronous communication and display it on the HTML page. This example is simple, but contains the main process of Ajax development using GWT.

Figure 7: gwtsample project structure

We noticed that there is a com. sample. myproject. server package in this project, which contains the code running on the server. The requests we send from the client are also sent to a servlet in this package.

For Asynchronous calls, the client must define an interface that inherits the remoteservice interface. In our example, we define the interface sampleservice. The sampleservice code is shown in Listing 4.

1    package com.sample.myProject.client;2    import com.google.gwt.user.client.rpc.RemoteService;3    public interface SampleService extends RemoteService{4    //The implementation of this method is used to return a string5    String getString();6    }

You have noticed that this interface inherits from remoteservice and declares the getstring () method. This method will be implemented in the server code. Of course, you may have realized that the declared method here is the method that can be called using the asynchronous call method.

After declaring this interface, we must declare another asynchronous call interface. In our example, this interface is sampleserviceasync. The method name declared in this interface must be the same as that in sampleservice, however, there are multiple parameters of the asynccallback type. The code list of the sampleserviceasync interface is shown in listing 5:

Listing 5: Sample serviceasync code list

1    package com.sample.myProject.client;2    import com.google.gwt.user.client.rpc.AsyncCallback;3    public interface SampleServiceAsync {4    void getString(AsyncCallback callback);5}

After the client defines the interface, we must implement this interface on the server. In our example, sampleserviceimpl implements the interface sampleservice, at the same time, you will notice that sampleserviceimpl also inherits the remoteserviceservlet class, while remoteserviceservlet is a subclass of httpservlet, so that our client requests can be submitted to servlet sampleserviceimpl. The code list of the sampleserviceimpl class is shown in Listing 6:

Listing 6: sampleserviceimpl code list

1    package com.sample.myProject.server;2    import com.google.gwt.user.server.rpc.RemoteServiceServlet;3    import com.sample.myProject.client.SampleService;4public class SampleServiceImpl extends RemoteServiceServlet implements 5 SampleService {6          public String getString() {7         return "This string is from server";8          }9}

Finally, let's take a look at the class democlient, which is the same type as the class democlient in the project myproject we created in the second part. However, in our project, we use it for asynchronous calls to the server. Listing 7 lists the code of the democlient class.

Listing 7: democlient code list

1    package com.sample.myProject.client;2    import com.google.gwt.core.client.EntryPoint;3    import com.google.gwt.core.client.GWT;4    import com.google.gwt.user.client.rpc.AsyncCallback;5    import com.google.gwt.user.client.rpc.ServiceDefTarget;6    import com.google.gwt.user.client.ui.Button;7    import com.google.gwt.user.client.ui.ClickListener;8    import com.google.gwt.user.client.ui.Label;9    import com.google.gwt.user.client.ui.RootPanel;10   import com.google.gwt.user.client.ui.Widget;/** * This class is used to demostrate hwo to  * interact with the server client in asynchronized * way */11   public class DemoClient implements EntryPoint {12       public void onModuleLoad() {13final SampleServiceAsync sampleService = (SampleServiceAsync) 14 GWT.create(SampleService.class);15        ServiceDefTarget target = (ServiceDefTarget)sampleService;16        String staticResponseURL = GWT.getModuleBaseURL();17        staticResponseURL += "/getStringService";18        target.setServiceEntryPoint(staticResponseURL);19        20        final Label label = new Label();21        final Button button = new Button("Get String");        22        button.addClickListener(new ClickListener() {23            public void onClick(Widget sender) {24                sampleService.getString(new AsyncCallback() {25                    public void onSuccess(Object result) {26                        label.setText((String) result);27                    }28                    public void onFailure(Throwable caught) {29                        label.setText(caught.getMessage());30                    }31                });32            }33        });34        RootPanel.get("1").add(button);35        RootPanel.get("2").add(label);36    }37}

Line 1 of the Code generates an instance of classes that implement the sampleserviceasync interface. Row 15th creates an instance of a servicedeftarget object, through which you can set the request destination. Line 2 of the Program sets the request destination URL. In our example, it is "/getstringservice". This URL will be mapped to servlet sampleserviceimpl in the web. xml file. Rows 22 to 33 of the program. The button we added sets the click RESPONSE event. In the response event, call the getstring (asynccallback callback) method of sampleservice. This method is used for asynchronous Remote Process calling (RPC ). in addition, the callback function is specified in the Code that implements the asynccallback interface. After the remote process is called successfully, the onsuccess (Object result) function is executed. The result contains the results returned from the server .. Run the onfailure (throwable caught) function after the remote engineering call fails. Add the button component and label component to the panel at the end of the program.

Now we have completed program development. Figure 8 shows the running result of our program. After clicking the button, a sentence is displayed on the right, what's important is that this sentence is obtained from the server asynchronously without page refresh. How do I want to use GWT for Ajax application development?

Figure 8: RPC call example

Summary

This article mainly introduces Ajax development with GWT, and compares it with the traditional Ajax development method, so that readers can better understand the differences between them, finally, we can see that using GWT for Ajax development can protect programmers from debugging JavaScript, and GWT automatically handles compatibility issues between browsers, which makes development easier and faster. Therefore, using GWT for Ajax development is a good method. I hope this article will help readers learn about GWT for Ajax development.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.