Google Web Toolkit (GWT) MVP Example (1)

本文介绍如何使用 Google Web Toolkit (GWT) 的 MVP 模式重构默认启动应用,通过引入最佳实践如命令模式、事件总线和依赖注入等,使应用更易于扩展和测试。

本文转自:http://blog.hivedevelopment.co.uk/2009/08/google-web-toolkit-gwt-mvp-example.html

 

 

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:

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-PresenterAn implementation of the MVP pattern;
GWT-DispatchAn implementation of the command pattern;
Google GinDependency Injection based on Google's Guice;
GWT-LogA 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:

log4jA logging framework;
Google Guice 2.0A 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:

google plugin eclipse create project 1 google plugin eclipse create project 2

This will generate the following structure:

gwt default application structure screenshot

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:

gwt default application screenshot

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:

gwt default application structure screenshot

Edit the GWT module definition file co.uk.hivedevelopment.greet/GreetMvp.gwt.xml:

view source
<object id="highlighter_777931_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash"> </object>
print ?
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.javaRepresents the main application;
GreetingView.javaThe GUI components for the greeting example;
GreetingPresenterThe business logic for the greeting example;
GreetingResponseViewThe GUI for the reponse popup;
GreetingResponsePresenterThe business logic for the response popup.
AppPresenter.java
view source
<object id="highlighter_644217_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash"> </object>
print ?
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.}
GreetingView.java
view source
<object id="highlighter_305023_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash"> </object>
print ?
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.}
学生社团系统-学生社团“一站式”运营管理平台-学生社团管理系统-基于SSM的学生社团管理系统-springboot学生社团管理系统.zip-Java学生社团管理系统开发实战-源码 更多学生社团系统: SpringBoot+Vue学生社团“一站式”运营管理平台源码(活动管理+成员考核+经费审批) Java学生社团管理系统开发实战:SSM升级SpringBoot(招新报名+场地预约+数据看板) 基于SpringSecurity的社团管理APP(移动端签到+权限分级+消息推送) 企业级社团数字化平台解决方案(SpringBoot+Redis缓存+Elasticsearch活动搜索) 微信小程序社团服务系统开发(活动直播+社团文化墙+成员互动社区) SpringBoot社团核心源码(多角色支持+工作流引擎+API接口开放) AI赋能社团管理:智能匹配兴趣标签+活动热度预测+成员贡献度分析(附代码) 响应式社团管理平台开发(PC/移动端适配+暗黑模式+无障碍访问) 完整学生社团系统源码下载(SpringBoot3+Vue3+MySQL8+Docker部署) 高校垂直领域社团平台:百团大战系统+社团星级评定+跨校活动联盟 适用对象:本代码学习资料适用于计算机、电子信息工程、数学等专业正在做毕设的学生,需要项目实战练习的学习者,也适用于课程设计、期末大作业。 技术栈:前端是vue,后端是springboot,项目代码都经过严格调试,代码没有任何bug! 核心管理:社团注册、成员管理、权限分级 活动运营:活动发布、报名签到、场地预约 资源服务:经费申请、物资管理、文档共享 数据分析:成员活跃度、活动效果评估、社团影响力排名
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值