[] [Xiao Jing] [developerworks China]
Ajax is used to create Web applications that are more dynamic and interactive. Google Web Toolkit (GWT) is an Ajax application development kit launched by Google. GWT allows developers to develop Ajax applications in Java. This article describes how to use GWT to develop Ajax applications.
Ajax Introduction
Ajax is short for Asynchronous JavaScript and XML (and DHTML). It is a combination of XHTML, CSS, JavaScript, XMLHttpRequest, XML, and other technologies. It is a popular technology in the field of Web application development, it is used to create more dynamic and interactive web applications and improve the user's browsing experience.
The core of AJAX is the JavaScript Object XMLHttpRequest. XMLHttpRequest is a technology that supports asynchronous requests to process objects that communicate with all servers. In short, XMLHttpRequest allows you to use JavaScript to request and process responses to the server without blocking users.
Ajax is not the focus of this article, so I will not go into details here. Please visit the relevant links in the resource area to learn more about Ajax technology and application.
Why choose GWT?
As we all know, even for developers who are very familiar with Ajax technology, the development and Debugging Processes of Ajax applications are not an easy task. What's more difficult is that, until now, no proper development tools have been available to support the development and debugging of Ajax applications.
On the contrary, the development and Debugging Processes of the Java language, the mainstream language for enterprise application development, are much simpler because of the support of various development tools, we can also obtain such development tools for free, such as Eclipse and netbeans.
If AJAX can be developed using the Java language, the biggest problem of AJAX application development-the lack of development tools-will be solved. In this case, we can make full use of the Java development advantages to reduce the difficulty of AJAX application development, speed up the development of Ajax applications, and create possibilities for large-scale Ajax applications, it can also take full advantage of Ajax technology to create more dynamic and interactive web applications and improve user browsing experience.
The emergence of Google Web Toolkit (GWT) provides us with this possibility. GWT is an Ajax application development kit launched by Google. It allows developers to develop Ajax applications in Java. The GWT framework itself is open-source, but the development tools in GWT only provide license for development and cannot be distributed.
GWT provides a set of Java-based Development Kits. for the design of this development kit, refer to the Java AWT package design. The class naming rules, interface design, and event listening are similar to AWT. Developers familiar with Java AWT can quickly understand the GWT development kit without much effort, and devote more time to the Development of GWT applications.
The developed Java application is compiled by the compilation tool provided by the GWT development kit, and then generates the corresponding Ajax web application, the interaction between Java applications and servers is replaced by the automatically generated asynchronous call code.
GWT features
GWT not only supports converting applications developed using the Java language into Ajax applications, but also provides more advanced features. The following is a simple description of these features.
1. GWT Compiler
GWT compiler is the core of GWT and is responsible for translating Java code into Ajax content. The GWT compiler can translate most of Java language features. This includes the support for basic types and violation handling in the Java language, the support for most classes and interfaces in the Java. lang Package and Java. util package, and the support for regular expressions and serialization.
2. cross-platform support
If you use the display components (such as buttons) and assembly components (such as verticalpanel) provided by GWT, the Ajax applications generated by GWT compilation can support most browsers and operating systems, for example, Internet Explorer and Firefox support different operating systems such as Linux and Windows. This is because GWT maximizes the translation of these controls into the class type built in the browser. For example, after the button class is compiled, the standard HTML is generated: <input type = "button">.
We recommend that you use CSS to modify the Display Effect of page elements. The GWT class rarely provides methods to access the style attributes of page elements. We can set the default display effect of page elements through the corresponding style names in the CSS file. For example, use. GWT-button {font-size: 150%;} to use the default display effect of the button element.
3. Host Mode)
The Host Mode refers to the state in which we interact with a GWT application that is not converted to an Ajax application. When we develop and debug, we are always in the host mode. In this case, the Java virtual machine uses the built-in GWT browser to run the class content compiled by the GWT application, so it can provide the optimal speed for the "encoding, testing, debugging" process.
We can run com. Google. GWT. Dev. gwtshell to start the host mode.
4. Web Mode)
The Web mode refers to the State that has been successfully converted to an Ajax application. In this state, we have begun to access the Ajax application through web.
When running in Web mode, GWT toolkit or JVM support is no longer required.
5. command line tool
The GWT toolkit provides several very useful gadgets to help us build a faster GWT Application Development Environment: projectcreator, applicationcreator, and junitcreator.
- Projectcreator
Create the basic project files and optional ant buildfile files required for GWT application development in eclipse.
- Applicationcreator
The applicationcreator command is used to create a basic helloworld! Application and GWT application development environment.
- Junitcreator
Generate the junti test code.
Through the above content, we have learned the basic principles and main features of the GWT tool set. If you can't wait, please join me in the GWT application development process and enjoy the simplicity and convenience of developing Ajax applications using Java.
All the environment preparations, instance development, and descriptions in this article are for the Windows operating platform. If you use other operating systems, make appropriate adjustments based on the actual situation.
Environment preparation
1. Download and install jdk1.4.x
The compilation of the GWT toolkit requires JDK support. Therefore, download and install the appropriate JDK before installing the GWT toolkit. GWT tool supports Java 1.4 or earlier versions. Therefore, JDK 1.4.x is suitable and the latest JDK or later version is not required.
Please visit the java.sun.com website to download the installation version, download it, and install it in the C:/JDK directory. The subsequent content in this book will use the % java_home % variable to reference this directory.
You can install JDK in any directory as needed. However, when running the example in this article, remember to replace the corresponding % java_home % variable with your actual installation directory.
2. Download and install GWT
Please visit ingress. This directory will be referenced using the % gwt_home % variable in subsequent content in this book.
The GWT toolkit supports different operating systems. select an appropriate installation package based on your operating system.
You can install GWT in any directory as needed. However, when running the example in this article, remember to replace the corresponding % gwt_home % variable with your actual installation directory.
Example 1-Hello world!
The following describes how to use the GWT tool set to complete the first GWT example-"Hello world! ", And will use GWT to compile and convert it into an Ajax application, complete the test in the browser.
The example to be completed includes:
- 1. display a button on the page
- 2. Click this button. By default, the string "Hello World!" is displayed after the button! ".
- 3. If you click "Hello World! "The string is already displayed in the browser. We need to hide it. Now we are using the GWT tool set to complete "Hello world! "For example development, the following steps are completed:" Hello world! "The basic steps for configuration, application development, and compilation in the example development environment are also applicable to the development of other GWT applications, but may be increased or decreased according to the actual situation.
1. Create a GWT Application Development Environment
From the above GWT features, we know that the applicationcreator command line tool provided by the GWT Toolkit can help us create the environment required for GWT application development, therefore, we can directly use applicationcreator to help us complete this task.
Open the command line tool, go to the C:/root directory, and run the "mkdi" command to create a new file directory helloworld.
Run the following command to add the % java_home %/bin directory and % gwt_home % directory to the path.
C:/> set Path = % java_home %/bin; % gwt_home % |
Replace % java_home % in the command line with the JDK installation directory in the actual environment, and replace % gwt_home % with the installation directory of the GWT toolkit.
Go to the newly created helloworld directory and run the applicationcreator command to create the GWT application development environment.
The syntax supported by the applicationcreator. CMD command is as follows.
Applicationcreator [-Eclipse projectname] [-out dir] [-overwrite] [-ignore] classname. The most important parameter is classname, that is, the main Java class in the GWT application we created. Here we choose to use Org. vivianj. GWT. client. helloworld.
C:/helloworld> applicationcreator. CMD org. vivianj. GWT. Client. helloworld |
According to the default rules of the GWT toolkit, the last part of the main Java class registration in the GWT application must be the client. That is to say, only Java classes named like XXX. Client. xxxx can be recognized as the correct main class of the GWT application.
When the applicationcreator tool is running, the following content is printed on the screen.
Created directory c:/helloworld/src
Created directory c:/helloworld/src/org/vivianj/GWT
Created directory c:/helloworld/src/org/vivianj/GWT/client
Created directory c:/helloworld/src/org/vivianj/GWT/Public
Created file C:/helloworld/src/org/vivianj/GWT/helloworld. GWT. xml
Created file C:/helloworld/src/org/vivianj/GWT/public/helloworld.html
Created file C:/helloworld/src/org/vivianj/GWT/client/helloworld. Java
Created file C:/helloworld/HelloWorld-shell.cmd
Created file C:/helloworld/HelloWorld-compile.cmd
2. Develop "Hello world! "Example
When using the applicationcreator tool, the applicationcreator tool has actually helped us generate a hello World! All content required by the example. To avoid interrupting the demo process of the first example, let's take a brief look at the generated content of the applicationcreator tool. We will make a more detailed analysis after the test process.
Figure 1 shows the directory structure generated after the applicationcreator tool is executed.
Figure 1 GWT Application Development Environment
Helloworld in src/org/vivianj/GWT/client directory in Figure 1. java is the main class of GWT applications; the helloworld.html file in src/org/vivianj/GWT/publicdirectory is the default page of the example; the helloworld under the src/org/vivianj/GWT directory. GWT. XML is the configuration file of the GWT application, providing the configuration information of pages and main classes in the GWT application; The HelloWorld-compile.cmd file under the root directory is used to provide the command to compile the GWT application into Ajax; the HelloWorld-shell.cmd file under the root directory is used to start the hosted mode for testing the GWT application.
3. Start "Hello World!" in host mode! "Example
We can run the HelloWorld-shell.cmd directly in the command line to start the host mode and run the newly created "Hello world! "Example.
C:/helloworld> HelloWorld-shell.cmd |
This command will start two visual interfaces: Google Web Toolkit development shell (see figure 2) and GWT's built-in GWT application browser (see figure 3). "Hello World!" will be displayed in the GWT application browser! "Example of the initial interface, If we click the" Click me "button on the interface, the button will show" Hello world! "String (see figure 4). If you click the" Click me "button on the page again, the" Hello world! "The string will disappear.
Figure 2 Google Web Toolkit development Shell Running Interface
Figure 3 "Hello world! "Example initial running interface
Figure 4 "Hello world! "Example-click the" clieck me "button.
4. Compile "Hello world! "Example
To compile a GWT application into an Ajax application, we can execute a HelloWorld-compile.cmd.
C:/helloworld> HelloWorld-compile.cmd
When the command is run, the following content is displayed on the interface.
Output will be written into C:/helloworld/www/org. vivianj. GWT. helloworld Copying all files found on public path Compilation succeeded |
The first line shows that the generated Ajax application is located in the C:/helloworld/www/org. vivianj. GWT. helloworld directory.
Figure 5 "Hello world! "Example: compiled directory structure
From the figure above, we can see that the newly generated WWW directory is named Org. vivianj. GWT. helloworld directory. Its naming rule is the full name of the GWT main class (Org. vivianj. GWT. client. helloworld) remove the "client. ".
The helloworld.html file in the org.vivianj.gwt.helloworlddirectory is "Hello world! "For example, the page ending with the suffix .cache.html is" Hello world! "The corresponding Ajax code section in the example, while the GWT. js file is the Javascript public function provided by GWT and needed in Ajax code. There are other auxiliary files.
5. Test "Hello World!" in Web mode! "Example
After running the HelloWorld-compile.cmd, The GWT application has been compiled into the Ajax application, no longer dependent on the JDK and GWT environment, but only rely on the browser.
Open the IE browser, open the C:/helloworld/www/org. vivianj. GWT. helloworld/helloworld.html file, and you will see "Hello world! "For the running effect of the example in Web mode (see Figure 6), click the" Click me "button on the page." Hello world! "String (see figure 7). If you click the" Click me "button on the page again, the" Hello world! "The string will disappear.
Figure 6 run "helloworld!" in Web Mode! "Default effect of the example
Figure 7 run "helloworld!" in Web Mode! "Example-effect after clicking" Click me"
Detailed instance analysis
In the above steps, we have completed the compilation and testing of the first GWT application. Next we will introduce in detail several files involved in the GWT Application Development Process: display page helloworld.html, main class helloworld, and configuration file helloworld. GWT. XML.
1. Display page helloworld.html
The HTML content of the GWT application must be stored in the public directory. the full path of the public directory is ORG/vivianj/GWT/ublic, which is the package name of the main class helloworld "org. vivianj. GWT. the directory structure formed after the client is replaced with "public.
We will introduce the content related to gwtin helloworld.html. For details about all the content of the helloworld.html file, see List 1.
24. <meta name = 'gwt: module' content = 'org. vivianj. GWT. helloworld'> |
In the 24th line of the helloworld.html file, we use the meta tag to specify the page and the GWT module "org. vivianj. GWT. the relationship between helloworld and meta tags. The name attribute of the meta tag remains unchanged, while the content attribute is the full name of the GWT main class (Org. vivianj. GWT. client. helloworld) remove the "client..
40. <script language = "JavaScript" src = "GWT. js"> </SCRIPT> |
In line 2 of the helloworld.html file, we use the script tag to introduce the default function library provided by the GWT tool. According to the requirements of the HTML language, we can choose to add this line of code between them or between them. We recommend that you add this line of code between GWT to get a little faster startup speed.
56. <TD id = "slot1"> </TD> <TD id = "slot2"> </TD> |
In the 56th rows of the helloworld.html file, we use the TD tag to define two adjacent table cells, named "slot1" and "slot2" respectively, according to "helloworld! "The example requires that a button should be displayed in the cell named" slot1 ", while a cell named" slot2 "will display" helloworld! "String or no content is displayed.
In the main class helloworld. use rootpanel in Java source code. get ("slot1") to get reference to this cell. For more information, see the "Main class helloworld" section below.
43. <IFRAME id = "_ gwt_historyframe" style = "width: 0; Height: 0; Border: 0"> </iframe> |
In the 43rd rows of helloworld.html, we use the IFRAME tag to set the current page to support the history function. The IFRAME attribute must be consistent with the above content, otherwise it will not have any effect.
Listing 1 src/org/vivianj/GWT/public/helloworld.html
1. <HTML>
2. 3.
4. <! -->
5. <! -- Any title is fine -->
6. <! -->
7. <title> wrapper HTML for helloworld </title>
8.
9. <! -->
10. <! -- Use normal HTML, such as style -->
11. <! -->
12. <style>
13. Body, TD, A, Div,. P {font-family: Arial, sans-serif}
14. Div, TD {color :# 000000}
15. A: Link,. W,. w a: link {color: # 0000cc}
16. A: visited {color: # 551a8b}
17. A: Active {color: # ff0000}
18. </style>
19.
20. <! -->
21. <! -- The module reference below is the link -->
22. <! -- Between HTML and your Web Toolkit Module -->
23. <! -->
24. <meta name = 'gwt: module' content = 'org. vivianj. GWT. helloworld'>
25.
26. 27.
28. <! -->
29. <! -- The body can have arbitrary HTML, or -->
30. <! -- You can leave the body empty if you want -->
31. <! -- To create a completely dynamic UI -->
32. <! -->
33. <body>
34.
35. <! -->
36. <! -- This script is required Bootstrap stuff. -->
37. <! -- You can put it in the head, but startup -->
38. <! -- Is slightly faster if you include it here. -->
39. <! -->
40. <script language = "JavaScript" src = "GWT. js"> </SCRIPT>
41.
42. <! -- Optional: Include this if you want history support -->
43. <IFRAME id = "_ gwt_historyframe"
Style = "width: 0; Height: 0; Border: 0"> </iframe>
44.
45. 46.
47. <p>
48. This is an example of a host page for the helloworld application.
49. You can attach a Web Toolkit Module to any HTML page you like,
50. making it easy to add bits of Ajax functionality to existing
Pages
51. Without starting from scratch.
52. </P>
53.
54. <Table align = center>
55. <tr>
56. <TD id = "slot1"> </TD> <TD
Id = "slot2"> </TD>
57. </tr>
58. </table>
59. </body>
60.
2. Main class helloworld
The main class helloworld must inherit from the com. Google. GWT. Core. Client. entrypoint class and overwrite its public void onmoduleload () method.
In the onmoduleload () method, we use the default display components (such as button) and assembly components (such as verticalpanel) provided in GWT to design the interface to be displayed, all these components are located at com. google. GWT. user. client. under the UI package. The naming rules of these components are similar to those of Java AWT, and the usage is basically the same as that of AWT. However, GWT provides many new components to choose from, for example, verticalpanel can be directly used for vertical layout management.
Lines 19 and 20 in helloworld. Java declare the two display components "button" and "label.
19. Final button = new button ("Click me "); 20. Final label Label = new label (); |
In the onmoduleload () method, we need to add the generated display components or assembled components to the corresponding display area of the display page. First, we need to use the ID attribute on the page to specify a unique name for the display area (see 56 rows in Listing 1 ). Com. google. GWT. user. client. UI. the static get method of rootpanel can obtain the corresponding display area on the page based on the input string parameters (the parameter value is the ID attribute of the display area.
Helloworld. for lines 36 and 37 of Java, the get method of rootpanel is used to obtain the display area with ID "slot1" and "slot2" respectively on the page, call the add method to add the generated button and label objects to the display area.
36. rootpanel. Get ("slot1"). Add (button ); 37. rootpanel. Get ("slot2"). Add (Label ); |
The most important function of AJAX is to provide users with a better interactive experience. GWT uses the same event listening mechanism as awt to Monitor client events, listener interfaces supported by GWT include changelistener and clicklistener. We can use various listener interfaces to obtain the actions on the user interface and process these actions to complete the corresponding business logic.
Line 22nd in helloworld. Java ~ The 29-line content implements a clicklistender interface and provides the onclick method for processing the business logic after the button is clicked (determine whether to display "Hello world! "String), and then call the addclicklistener method of the button object to add the listener.
22. Button. addclicklistener (New clicklistener (){ 23. Public void onclick (widget sender ){ 24. If (Label. gettext (). Equals ("")) 25. Label. settext ("Hello world! "); 26. Else 27. Label. settext (""); 28 .} 29 .}); |
For the full source code of the helloworld class, see List 2.
Listing 2 src/org/vivianj/GWT/client/helloworld. Java
1. Package org. vivianj. GWT. client;
2.
3. Import com. Google. GWT. Core. Client. entrypoint;
4. Import com. Google. GWT. User. Client. UI. Button;
5. Import com. Google. GWT. User. Client. UI. clicklistener;
6. Import com. Google. GWT. User. Client. UI. label;
7. Import com. Google. GWT. User. Client. UI. rootpanel;
8. Import com. Google. GWT. User. Client. UI. widget;
9.
10 ./**
11. * entry point Classes define <code> onmoduleload () </code>.
12 .*/
13. Public class helloworld implements entrypoint {
14.
15 ./**
16. * This is the entry point method.
17 .*/
18. Public void onmoduleload (){
19. Final button = new button ("Click me ");
20. Final label Label = new label ();
21.
22. Button. addclicklistener (New clicklistener (){
23. Public void onclick (widget sender ){
24. If (Label. gettext (). Equals (""))
25. Label. settext ("Hello world! ");
26. Else
27. Label. settext ("");
28 .}
29 .});
30.
31. // assume that the host HTML has elements defined whose
32. // IDs are "slot1", "slot2". In a real app, you probably wocould not want
33. // to hard-code IDs. Instead, you cocould, for example, search for all
34. // elements with a particle CSS class and replace them with widgets.
35 .//
36. rootpanel. Get ("slot1"). Add (button );
37. rootpanel. Get ("slot2"). Add (Label );
38 .}
39 .}