Here at Hive Development, I'm currently working on the GWT based UI for a new website/RIA monitoring service called SiteAlright. I recommend you head over and check it out. As you might expect we try to follow best practises when developing our apps and there's been quite a lot of talk recently on GWT Google Groups regarding the use of elements from the recent talk by Ray Ryan at Google I/O 2009 entitled Google Web Toolkit Architecture: Best Practices For Architecting Your GWTApp.
This excellent talk laid out several best practise approaches for architecting your GWT application based on the team's experiences while developing the new AdWords interface. Some of the key recommendations were:
- Use an MVP pattern;
- Use a command pattern;
- Use an Event Bus (a.k.a Event Collaboration);
- Use Dependency Injection.
The aim of this tutorial is to demonstrate these GWT best practises by applying them the default starter application generated by the Google Plugin for Eclipse.
There are many benefits to these patterns and I'll leave it to the links above to go into these in detail. However, using these patterns the bottom line is that your GWT application will be:
- Easier to extend - well defined structure makes the addition of new business logic much easier;
- Easier to test - the decoupling makes quick unit testing of commands, events and presenters not only possible but easy;
- GWT's History mechanism is baked into your application from the start - this is crucial for a GWT application and is a pain to retro-fit;
MVP Web Application Starter Project
For this tutorial I'm using Eclipse with the Google Plugin for Eclipse. With the Google plugin when you create a GWT project, it also creates a useful starter application with some widgets and server components. This tutorial will work with this starter application and will apply the above patterns.
Although this example has all the source code and references to required resources, you may download the complete GreetMvp project for Eclipse 3.5 from here.
As well as the Google plugin, you'll also need the following GWT libraries:
| GWT-Presenter | An implementation of the MVP pattern; |
| GWT-Dispatch | An implementation of the command pattern; |
| Google Gin | Dependency Injection based on Google's Guice; |
| GWT-Log | A log4j-style logger for GWT. |
NOTE: currently GIN needs to be built from source using SVN/Ant.
You'll also need the following libraries at the server:
| log4j | A logging framework; |
| Google Guice 2.0 | A dependency injection framework for Java. |
After introducing these best practise patterns, the structure starter application will be transformed. At this point, it's probably worth noting that:
- You'll no longer make RPC service calls directly - these are wrapped up in the command pattern and are handled by the gwt-dispatch library;
- The main page and the server response popup will be separated into respective view/presenters;
- The Event Bus pattern is implemented using the GWT 1.6+ Handlers mechanism.
Unsurprisingly, the code size will jump from the initial starter app, but what you'll end up with offers much more and will hopefully serve as the starting point for a real application based on these best practises.
Let's begin.
Fire up Eclipse and generate your starter application, I've called it GreetMvp:
This will generate the following structure:
If you're not already familiar with the default application I suggest you take a look at the entry point class which in my case is co.uk.hivedevelopment.greet.client.GreetMvp.java. You'll see all the view code, custom handler logic and server calls all lumped into one method. Fire up the application and you see the following:
The first thing we'll do is add the required libraries to the project - at this point you should have downloaded the listed dependencies and built Google Gin.
Create a folder called lib in your project at the top level of your project for client-only libraries and add the following:
| gin.jar |
For server and client dependencies, add the remaining jars into the web application lib folder located at war/WEB-INF/lib:
| aopalliance.jar | (from Google Gin) |
| guice-2.0.jar | (from Google Gin. IMPORTANT - use the version supplied with Gin and not Guice) |
| guice-servlet-2.0.jar | (from Google Guice) |
| gwt-dispatch-1.0.0-SNAPSHOT.jar | (from gwt-dispatch) |
| gwt-log-2.6.2.jar | (from gwt-log) |
| gwt-presenter-1.0.0-SNAPSHOT.jar | (from gwt-presenter) |
| log4j.jar | (from log4j) |
Add all of the above jars to the project's build path. You should have something that looks similar to this:
Edit the GWT module definition file co.uk.hivedevelopment.greet/GreetMvp.gwt.xml:
01.
<?xml version="1.0" encoding="UTF-8"?>
02.
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">
03.
<module rename-to='greetmvp'>
04. <!-- Inherit the core Web Toolkit stuff. -->
05.
<inherits name="com.google.gwt.user.User" />
06.
<inherits name="com.google.gwt.inject.Inject" />
07.
<inherits name='net.customware.gwt.dispatch.Dispatch' />
08.
<inherits name='net.customware.gwt.presenter.Presenter' />
09. <!-- Inherit the default GWT style sheet. You can change -->
10. <!-- the theme of your GWT application by uncommenting -->
11. <!-- any one of the following lines. -->
12.
<inherits name='com.google.gwt.user.theme.standard.Standard' />
13. <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
14. <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
15. <!-- Specify the app entry point class. -->
16.
<entry-point class='co.uk.hivedevelopment.greet.client.GreetMvp' />
17. <!-- Add gwt-log support, default level `OFF` - check for
18. extended property 'log_level' to see if this is overridden -->
19.
<inherits name="com.allen_sauer.gwt.log.gwt-log-OFF" />
20. <!-- Also compile Logger at `INFO` level -->
21.
<extend-property name="log_level" values="INFO" />
22.
<set-property name="log_level" value="INFO" />
23. <!-- Turn off the floating logger - output will be shown in the
24. hosted mode console -->
25.
<set-property name="log_DivLogger" value="DISABLED" />
26.
27.
<source path="shared" />
28.
<source path="client" />
29.</module>
Note the <source> tags. We have roughly 3 top level packages defined: client, shared and server. We do not want GWT accessing the server sub-packages so we have explicity told the GWT compiler what it can access.
Try to compile the project, it should compile cleanly.
Create View and Presenters
Now we'll split the app into the following components:
| AppPresenter.java | Represents the main application; |
| GreetingView.java | The GUI components for the greeting example; |
| GreetingPresenter | The business logic for the greeting example; |
| GreetingResponseView | The GUI for the reponse popup; |
| GreetingResponsePresenter | The business logic for the response popup. |
01.
package co.uk.hivedevelopment.greet.client.mvp;
02.
import net.customware.gwt.dispatch.client.DispatchAsync;
03.
import com.google.gwt.user.client.ui.HasWidgets;
04.
import com.google.inject.Inject;
05.
public class AppPresenter {
06.
private HasWidgets container;
07.
private GreetingPresenter greetingPresenter;
08. @Inject
09.
public AppPresenter(final DispatchAsync dispatcher,
10.
final GreetingPresenter greetingPresenter) {
11. this.greetingPresenter = greetingPresenter;
12. }
13.
14.
private void showMain() {
15. container.clear();
16. container.add(greetingPresenter.getDisplay().asWidget());
17. }
18.
19.
public void go(final HasWidgets container) {
20. this.container = container;
21.
22. showMain();
23. }
24.}
01.
package co.uk.hivedevelopment.greet.client.mvp;
02.
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
03.
import com.google.gwt.event.dom.client.HasClickHandlers;
04.
import com.google.gwt.user.client.ui.Button;
05.
import com.google.gwt.user.client.ui.Composite;
06.
import com.google.gwt.user.client.ui.FlowPanel;
07.
import com.google.gwt.user.client.ui.HasValue;
08.
import com.google.gwt.user.client.ui.RootPanel;
09.
import com.google.gwt.user.client.ui.TextBox;
10.
import com.google.gwt.user.client.ui.Widget;
11.
public class GreetingView extends Composite implements GreetingPresenter.Display {
12.
private final TextBox name;
13.
private final Button sendButton;
14.
public GreetingView() {
15.
final FlowPanel panel = new FlowPanel();
16. initWidget(panel);
17.
name = new TextBox();
18. panel.add(name);
19.
sendButton = new Button("Go");
20. panel.add(sendButton);
21.
22. // Add the nameField and sendButton to the RootPanel
23. // Use RootPanel.get() to get the entire body element
24. RootPanel.get("nameFieldContainer").add(name);
25. RootPanel.get("sendButtonContainer").add(sendButton);
26.
27. reset();
28. }
29.
public HasValue getName() {
30.
return name;
31. }
32.
public HasClickHandlers getSend() {
33.
return sendButton;
34. }
35.
36.
public void reset() {
37. // Focus the cursor on the name field when the app loads
38. name.setFocus(true);
39. name.selectAll();
40. }
41. /**
42. * Returns this widget as the {@link WidgetDisplay#asWidget()} value.
43. */
44.
public Widget asWidget() {
45.
return this;
46. }
47. @Override
48.
public void startProcessing() {
49. }
50. @Override
51.
public void stopProcessing() {
52. }
53.}
本文介绍如何使用 Google Web Toolkit (GWT) 的 MVP 模式重构默认启动应用,通过引入最佳实践如命令模式、事件总线和依赖注入等,使应用更易于扩展和测试。
359

被折叠的 条评论
为什么被折叠?



