Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks

Introduction

GWT is a Java framework that allows you to easily develop AJAX (Asynchronous JavaScript and XML) based web applications. This tutorial will teach you how to create and use Serializable objects that can be transported over GWT’s RPC mechanism. If you haven’t already please read our previous tutorials: Introduction to GWT, Anatomy of a GWT Project, and Building a GWT RPC Service.

To learn more about GWT, I recommend reading these good books – GWT Solutions, GWT Applications, AJAX Security.

GWT RPC and Serialization

One of the most important pieces of the GWT framework is the GWT Remote Procedure Call (RPC) mechanism. This RPC mechanism makes it easy for a GWT application client to make acall to server-side services. GWT RPC makes it simple to get data between the client and the server.

What is Serialization?

Serialization is the process of transmitting an object across a network connection in binary form. Because GWT RPC calls are between JavaScript and Java code, GWT provides object serialization as part of its RPC mechanism. Please note that GWT serialization is not the same as Java serialization.

Serializable Types

Any object that needs to be sent between the client and server has to be a GWT serializable type. A type is serializable and can be used in a service interface if the type:

  • is primitive, such as char, byte, short, int, long, boolean, float, or double;
  • is String, Date, or a primitive wrapper such as Character, Byte, Short, Integer, Long, Boolean, Float, or Double;
  • is an array of serializable types (including other serializable arrays);
  • is a serializable user-defined class; or
  • has at least one serializable subclass

GWT Serialization demo – The Contact List Application

A simple GWT application that gets a list of Contacts from the server will be used to demonstrate GWT RPC’s serialization mechanism. The Contact List Application is a simple GWT application where a user can click on a button to make a GWT service call to retrieve a list of contacts.

Creating a user defined GWT Serializable Class

A user defined class is serializable if:

  • the class is assignable to IsSerializable or java.io.Serializable, either because it implements one of these interfaces, or because it is derived from a superclass that implements one of these interfaces.
  • all the class’s non-final, non-transient instance fields are serializable
  • the class has a public default (zero argument) constructor

The heart of the Contact List Application is the Contact class. The Contact class consists of a HashMap of Strings that stores contact information. The HashMap key is a String that signifies the type of contact information, e.g. name, e-mail address, street address, phone number, etc. The Contact List Application’s client UI will consist of a display area and a button that allows the user to make a GWT service call to retrieve all the Contacts. The GWT service will return an ArrayList of Contact objects.

Type Arguments – How to make serializable Collections in GWT

Collection classes such as java.util.Map and java.util.List represent a collection of Object instances. To make collections serializable, you must specify the type of objects the collections are expected to contain. This is achieved through the use of a special Javadoc annotation: @gwt.typeArgs. This annotation is necessary to enable the GWT proxy generator to create efficient code. Defining the item type for a collection ensures that the collection only ever contains objects of that item type, or a subclass thereof. Be careful to only add objects of the asserted item type to a collection. Adding an object to a collection that violates its asserted item type will lead to undefined and anomalous behavior.

The code below shows you how to define and implement the Serializable Contact class. This demonstrates how to create a serializable user-defined class that has a Collection as a field. As you can see from the echoContactList method, there is no need to specify the name of the field in the @gwt.typeArgs declaration since it can be inferred.

   1: public class Contact implements IsSerializable {
   2:   /**
   3:    * HashMap that will always contain strings for both keys and values
   4:    * @gwt.typeArgs <java.lang.String, java.lang.String>
   5:    */
   6:   private HashMap contactInfo;
   7:
   8:
   9:   /**
  10:    * Default Constructor
  11:    */
  12:   public Contact() {
  13:     contactInfo = new HashMap();
  14:     contactInfo.put("name", "");
  15:     contactInfo.put("email", "");
  16:     contactInfo.put("address", "");
  17:     contactInfo.put("phone", "");
  18:   }
  19:
  20:
  21:   /**
  22:    * Method used to set the contact's name
  23:    * @param name  contact's name
  24:    */
  25:   public void setName(String name) {
  26:     contactInfo.put("name", name);
  27:   }
  28:
  29:
  30:   /**
  31:    * Method used to set the contact's email address
  32:    * @param email  contact email address
  33:    */
  34:   public void setEmail(String email) {
  35:     contactInfo.put("email", email);
  36:   }
  37:
  38:
  39:   /**
  40:    * Method used to set the contact's street address
  41:    * @param address contact's street address
  42:    */
  43:   public void setAddress(String address) {
  44:     contactInfo.put("address", address);
  45:   }
  46:
  47:
  48:   /**
  49:    * Method used to set the contact's phone number
  50:    * @param phoneNumber contact's phone number
  51:    */
  52:   public void setPhoneNumber(String phoneNumber) {
  53:     contactInfo.put("phone", phoneNumber);
  54:   }
  55:
  56:
  57:   /**
  58:    * Method used to get the contact's name
  59:    * @return  contact's name
  60:    */
  61:   public String getName() {
  62:     return (String) contactInfo.get("name");
  63:   }
  64:
  65:
  66:   /**
  67:    * Method used to get the contact's email address
  68:    * @return  contact's email address
  69:    */
  70:   public String getEmail() {
  71:     return (String) contactInfo.get("email");
  72:   }
  73:
  74:
  75:   /**
  76:    * Method used to get the contact's street address
  77:    * @return  contact's street address
  78:    */
  79:   public String getAddress() {
  80:     return (String) contactInfo.get("address");
  81:   }
  82:
  83:
  84:   /**
  85:    * Method used to get the contact's phone number
  86:    * @return  contact's phone number
  87:    */
  88:   public String getPhoneNumber() {
  89:     return (String) contactInfo.get("phone");
  90:   }
  91:
  92: } //end class Contact

The next step is to define and implement a service that returns a list of Contacts. The code below shows you how to define the service as well as how to annotate its method parameters and return types. As you can see, the parameter annotations must include the name of the parameter they are annotating along with the collection item type. Return type annotations do not need to include the name of what is being returned.

   1: public interface ContactListService extends RemoteService {
   2:   /**
   3:    * Method used to get a list of contacts
   4:    * @return  ArrayList of Contact objects
   5:    *
   6:    * @gwt.typeArgs <client.Contact>
   7:    */
   8:   public ArrayList getContactList();
   9:
  10:   /**
  11:    * Method used to echo a list of contacts. This method serves no real purpose other than to
  12:    * demonstrate how to annotate a service method.
  13:    * 
  14:    * @param listOfContacts contact list to echo
  15:    * @return  echoed contact list
  16:    * 
  17:    * @gwt.typeArgs listOfContacts <client.Contact>
  18:    * @gwt.typeArgs <client.Contact>
  19:    */
  20:   public ArrayList echoContactList(ArrayList listOfContacts);
  21:
  22: }

A Note about GWT RPC and Polymorphism

While GWT RPC supports polymorphic parameters and return types, it is best to try to be as specific as possible when defining service interfaces. Increased specificity allows the GWT Compiler to do a better job of optimizing your code and reducing the size of your application.

Does GWT support java.io.Serializable?

Prior to GWT version 1.4, the GWT RPC mechanism only used the IsSerializable marker interface to denote serializable classes. However, as of GWT version 1.4, the GWT RPC system does support limited use of java.io.Serializable but with one specific condition. Please note that this GWT still doesn’t support Java serialization. Support for the java.io.Serializable interface was added to make it easier for developers to use existing code with their GWT applications.

The GWT Compiler generates a serialization policy file (.gwt.rpc file). The serialization policy file contains a whitelist of types that can be serialized. In order to enable java.io.Serializable support, you need to include all the types that your application will send over the wire in the serialization policy whitelist. The serialization policy file must be deployed to your web server as a public resource and needs to be accessible from a RemoteServiceServlet via ServletContext.getResource(). If the serialization whitelist policy file is not deployed properly, your GWT application will run in 1.3.3 compatibility mode and refuse to serialize types implementing java.io.Serializable.

Contact list app screenshot

contactlist

Downloads

All the source code provided on this site is distributed under the Apache Open Source License v2.0.

  1. You can download the full source code used to build the Contact List Application here.
  2. You can download the WAR file to deploy the Contact List Application here.

Comments and Discussion

If you want to comment on this article, please click here.

Training Services

Want to learn from the best in the business? We have training programs available for BlackBerry development, Android development, rich desktop apps, and UX design. We can give your development team a competitive edge, and make them experts in these technologies. Contact us if you are interesting in learning more about our training services & schedule.

Consulting Services

If you need help building web, mobile, and desktop apps that are all connected to the cloud, we can help. We can empower your business by bringing your ideas to life. Contact us if you have a project you need our help with and we will consider taking you on as a client.

Our expertise: architecture, UX design, graphic design, and implementation services for BlackBerry, Android, GWT, desktop Java, and cloud computing. Our specialties: crafting stunning UXes, LBS, real-time collaboration and syncing between services and web/mobile/desktop apps, location based mobile e-commerce, and location based mobile advertising.

Further reading in related categories

GWT

GWT Tutorial - Managing History and Hyperlinks
When you are building GWT apps, that run in the context of a web browser, what should happen when the user of your app presses the Back or Forward button in their browser? GWT provides a way for your apps to hook into the browser's history mechanism, so that you can control what happens when a user hits Back or Forward in their browser. You can also programmatically manipulate the browser's history, and even create hyperlinks in your apps that can hook into the browser's history mechanism. You can even intercept these hyperlinks when a user clicks on them, instead of having the browser handle it, or both. This tutorial will show you how to leverage GWT's history mechanism and do some creative things with histories and hyperlinks that will be useful in your applications.
GWT Tutorial - Deploying GWT Apps
There are two aspects to deploying a GWT application: client side deployment, and server side packaging and deployment. In this tutorial, I will cover the different sets of issues that are tied to each aspect of deployment and packaging. Issues around cross site scripting, integration into existing webpages/apps, deployment as widgets, and much more are discussed in detail.
GWT Tutorial - Using Servlet Sessions in GWT
Because GWT web applications run inside of a browser, they are limited to making requests over HTTP. HTTP is a “stateless” protocol and it doesn’t provide any facilities for tracking previous transactions. In this tutorial you will learn how to use GWT’s RPC mechanism, specifically the RemoteServiceServlet, to enable session support in your GWT application.
GWT Tutorial - Using and creating modules
If you are trying to build a complex GWT application that needs to be split into multiple modules, or if you need to import 3rd party modules into your application, this tutorial will show you how to do both of these things. We will import the GWT Log module, and we will also create a new module that you can include as a dependency for other modules/projects.
GWT Tutorial - Create "Hello World" with IDEA
In this tutorial, I will walk you through the tasks you need to perform in IDEA 7 to create GWT projects. We will do the following: create a new project, add resources to it (images, stylesheets), create a web facet for deployment to an app server/servlet engine, add a loading screen for your app.
GWT Tutorial - Building a GWT RPC Service
One of the most important pieces of the GWT framework is the GWT Remote Procedure Call (RPC) mechanism. This RPC mechanism makes it easy for a GWT application client to make a call to server-side code. GWT RPC makes it simple to get data between the client and the server. The server-side code that gets called from the client is referred to as a service. This tutorial will teach you how to build a GWT RPC Service.
GWT Tutorial - Anatomy of a GWT Project
The first step in writing any GWT application is setting up a GWT Project. This tutorial will introduce you to the ins and outs of GWT projects.
GWT Tutorial - Introduction to GWT
An overview of GWT, what it does, how it does it , and who should use it.
posted on 2010-01-22 17:33 seal 阅读(1116) 评论(0)  编辑  收藏 所属分类: GWT

只有注册用户登录后才能发表评论。


网站导航: