SmartGWT Quick Start Guide
SmartGWT Quick Start Guide
SmartGWT Quick Start Guide
Copyright ©2010 and beyond Isomorphic Software, Inc. All rights reserved. The
information and technical data contained herein are licensed only pursuant to a license
agreement that contains use, duplication, disclosure and other restrictions; accordingly, it
is ―Unpublished-rights reserved under the copyright laws of the United States‖ for
purposes of the FARs.
Web: www.isomorphic.com
Disclaimer of Warranties
THE INFORMATION CONTAINED HEREIN IS PROVIDED ―AS IS‖ AND ALL EXPRESS
OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT AND ONLY TO
THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Contents
Contents .............................................................................. i
How to use this guide .............................................................. iii
Why Smart GWT? ..................................................................... v
More than Just Widgets – A Complete Architecture ......................v
Eliminates Cross-Browser Testing and Debugging.........................v
Complete Solution ......................................................................... vi
Open, Flexible Architecture .......................................................... vi
1. Overview.............................................................................. 1
Architecture ..................................................................................... 1
Capabilities and Editions of Smart GWT ....................................... 2
2. Installation ......................................................................... 3
Starting a New Project .................................................................... 3
Adding Smart GWT to an Existing Project..................................... 3
Server Configuration (optional) ..................................................... 4
3. Exploring .............................................................................5
Smart GWT Showcase .................................................................... 5
Smart GWT Java Doc ..................................................................... 6
Smart GWT Developer Console...................................................... 6
4. Visual Components ............................................................ 11
Component Documentation & Examples ...................................... 11
Drawing, Hiding, and Showing Components ................................ 12
Size and Overflow .......................................................................... 12
Handling Events ............................................................................ 13
5. Data Binding ...................................................................... 15
Databound Components ............................................................... 15
Fields ............................................................................................. 16
DataSources .................................................................................. 20
Customized Data Binding............................................................. 23
DataSource Operations ................................................................ 24
DataBound Component Operations ............................................. 26
Data Binding Summary ................................................................ 27
6. Layout .............................................................................. 28
Component Layout ....................................................................... 28
Container Components ................................................................ 30
Version 2.3 i
Contents Smart GWT Quick Start
ii Version 2.3
How to use this guide
The Smart GWT Quick Start Guide is designed to introduce you to the
Smart GWT™ web presentation layer. Our goals are:
This is an interactive manual. You will receive the most benefit from this
guide if you are working in parallel with the Smart GWT SDK—following
the documented steps, creating and modifying the code examples, and
finding your own paths to explore. You may want to print this manual for
easier reference, especially if you are working on a single-display system.
We assume that you are somewhat acquainted with basic concepts of web
applications (browsers, pages, tags), object-oriented programming
(classes, instances, inheritance), and user interface development
(components, layout, events). However, you do not need deep expertise in
any specific technology, language, or system. If you know how to navigate
a file system, create and edit text files, and open URLs in a web browser,
you can start building rich web applications with Smart GWT today.
Smart GWT helps you to build and maintain more usable, portable,
efficient web applications faster, propelled by an open, extensible stack
of industry-tested components and services.
In this chapter we explore the unique traits of the Smart GWT platform
that set it apart from other technologies with similar purpose.
The examples included with Smart GWT demonstrate the simplicity that
can only be achieved by a framework that addresses both server- and
client-side architectural concerns to deliver globally optimal solutions.
Even if you adopt only part of the Smart GWT solution, you benefit from
an architecture that takes into account the entire problem you need to
solve, not just a part of it. Every integration point in the Smart GWT
platform has been designed with a clear understanding of the
requirements you need to fulfill, and, the solutions built into Smart GWT
provide a ―blueprint‖ for one way of meeting those requirements.
Version 2.3 v
Why Smart GWT? Smart GWT Quick Start
Even if you need to create a totally unique look and feel, Smart GWT‘s
simplified skinning and branding requires only basic knowledge of page
styling, and you never have to deal with browser layout inconsistencies.
Complete Solution
By giving you both options, Smart GWT allows you to address a broader
range of projects with a single set of skills. You can even reuse existing
content and portlets by embedding them in Smart GWT user interface
components. Smart GWT allows a smooth evolution of your existing web
applications—you aren‘t forced to start over.
vi Version 2.3
Smart GWT Quick Start Why Smart GWT?
Finally, Smart GWT is completely extensible, all the way down to the
web standards on which the system is constructed. If you can‘t do
something ―out of the box,‖ you can build or buy components that
seamlessly extend Smart GWT in any manner you desire.
Version 2.3
vii
1. Overview
Architecture
The Smart GWT architecture spans client and server, enabling Rich
Internet Applications (RIAs) that communicate transparently with your
data and service tiers.
Client Server
Data Providers
GUI Rendering & Interactivity DataSource
Schema
Local
DataSource Binding Metadata and Operations
Operations
HTTP(S)
Communication Layer Communication Layer
XMLHttp
Within the web browser, Smart GWT provides a deep stack of services
and components for rich HTML5 / Ajax applications. For those using a
Java-based server, Smart GWT provides a server-side framework that can
be added to any existing Java web application.
Version 2.3 1
Overview Smart GWT Quick Start
Finally, note that Smart GWT does not require that you adopt this entire
architecture. You may choose to integrate with only the layers and
components that are appropriate for your existing systems and
applications.
Smart GWT comes in several editions, and the features included in each
of the editions are described on the SmartClient.com website at
http://www.SmartClient.com/product
The portions of this document that make use of Smart GWT server
components require the Pro license or above. None of the features
demonstrated in this document require more than a Pro license.
2 Version 2.3
2. Installation
To get started quickly, use the ―built-in-ds‖ sample project included in the
Smart GWT SDK under samples/built-in-ds. Within this directory, see
the README.txt file for instructions to import the project into the Eclipse
IDE or to run the project from the command line using Apache ant.
If you wish to install Smart GWT into a pre-existing project, see the step-
by-step setup guide (http://www.smartclient.com/smartgwtee/javadoc/
com/smartgwt/client/docs/SgwtEESetup.html).
For purposes of this Quick Start, we strongly recommend using one of the
sample projects, which have a pre-configured, embedded server and
database.
Version 2.3 3
Installation Smart GWT Quick Start
Settings that apply to servlets can be applied via the standard web.xml file.
See the JavaDoc for each servlet for details.
If you have any problems installing or starting Smart GWT, try the
Smart GWT Developer Forums at forums.smartclient.com.
4 Version 2.3
3. Exploring
http://www.smartclient.com/smartgwtee/showcase/
The Showcase is your best starting point for exploring Smart GWT
capabilities and code. For each example in the Showcase, you can view the
source code by clicking on the View Source button in the upper right side
of the example pane.
http://www.smartclient.com/smartgwt/showcase/
For all samples related to data binding, data loading and data integration,
focus on the samples in the EE Showcase while you are learning. The data
integration samples in the LGPL Showcase focus on concerns that become
irrelevant if you adopt Smart GWT Pro or better.
Version 2.3 5
Visual Components Smart GWT Quick Start
The core documentation for Smart GWT is the Smart GWT JavaDoc. You
can access the Smart GWT JavaDoc in any of the following ways:
Online:
In the SDK:
6 Version 2.3
Smart GWT Quick Start Visual Components
Version 2.3
7
Visual Components Smart GWT Quick Start
The Watch pane of the Developer Console displays a tree of Smart GWT
user interface components in the current application. With the built-in-ds
application running, this pane appears as follows:
8 Version 2.3
Smart GWT Quick Start Visual Components
The RPC tab shows requests for data issued by Smart GWT components.
Enable this tab by checking the ―Track RPCs‖ checkbox. This tool shows
you:
Version 2.3
9
Visual Components Smart GWT Quick Start
The Developer Console is an essential tool for all Smart GWT application
developers and should be open whenever you are working with Smart
GWT. For easy access, you should create a toolbar link to quickly show the
Console:
In Firefox/Mozilla:
In Internet Explorer:
3. Click on the small Isomorphic logo in the Address bar and drag
it to your Links toolbar.
10 Version 2.3
Smart GWT Quick Start Visual Components
4. Visual Components
Smart GWT provides two families of visual components for rich web
applications:
Version 2.3
11
Visual Components Smart GWT Quick Start
hide()
show()
The most basic properties for a visual component involve its size and
overflow:
width
height
overflow
In this example, the specified width is smaller than the contents of the
label, so the text wraps and ―overflows‖ the specified size of the label. This
behavior is controlled by the overflow property, which is managed
automatically by most components. You may want to change this setting
12 Version 2.3
Smart GWT Quick Start Visual Components
This will show a 10 pixel wide Label for which the text ―Hello World‖ is
clipped.
Handling Events
If a Smart GWT component has support for a given type of event, it will
implement a Java interface HasEventNameHandlers such as
HasClickHandlers. These interfaces allow registration of an EventHandler
object that receives an Event object when the event occurs.
For example:
import com.smartgwt.client.widgets.Button;
Version 2.3
13
Visual Components Smart GWT Quick Start
The Event object your event handler receives has methods that allow you
to retrieve information about the current event. For example, the
RecordClickEvent has a getRecord()method that allows you to retrieve the
Record that was clicked.
14 Version 2.3
5. Data Binding
Databound Components
This chapter outlines the client-side interfaces that you may use to
configure databound components and interact with their underlying
DataSources. Chapter 7, Data Integration, outlines the interfaces
for server-side integration of DataSources with your data and
service tiers.
Visual Components Smart GWT Quick Start
Fields
Component Fields
DynamicForm form controls
ListGrid columns & form controls
TreeGrid columns & form controls
Calendar event duration and description
ColumnTree columns & form controls
DetailViewer rows within blocks
TileGrid rows within tiles
CubeGrid (Analytics option) facets (row & column headers)
16 Version 2.3
Smart GWT Quick Start Visual Components
You can specify the displayed fields of a visual component via the
setFields() method, which takes an array of objects defining the fields
for that component. For example:
ListGrid grid = new ListGrid();
lastNameField.setName("lastname");
lastNameField.setTitle("Last Name");
grid.setFields(salutationField,
firstNameField,
lastNameField);
grid.draw();
Try running the example code above. When you load it in your web
browser, you should see a ListGrid that looks like this:
Version 2.3
17
Visual Components Smart GWT Quick Start
The name property of a field is the special key that connects that field to
actual data values. To add records to the fields, add this code to the
ListGrid definition above:
grid.setData(new ListGridRecord[] {
record1, record2, record3
});
18 Version 2.3
Smart GWT Quick Start Visual Components
The basic properties of field definitions (name, title) in the ListGrid above
are the same as the properties used across other components that support
data binding. For example, this very similar code creates a DynamicForm
for working with the same Records:
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
form.setFields(new FormItem[] {
salutationItem, firstNameItem, lastNameItem
});
form.draw();
com.smartgwt.client.widgets.form.fields
com.smartgwt.client.widgets.grid.ListGridField
Version 2.3
19
Visual Components Smart GWT Quick Start
DataSources
Note that use of the XML format requires the Smart GWT Server. The
Smart GWT Server can also derive DataSources from existing sources of
metadata formats such as Java Beans or SQL schema – see Chapter 8,
Smart GWT Server Framework, for details.
20 Version 2.3
Smart GWT Quick Start Visual Components
2. Add a <script> tag to your HTML bootstrap file that uses the
DataSourceLoader servlet to load the DataSource. For example,
in the ―built-in-ds‖ sample project, the bootstrap file is
war/BuiltinDS.html, and there is an existing <script> tag you
can add to. Change it to:
<script src="builtinds/sc/DataSourceLoader?dataSource=supplyItem,
animals,employees,contacts"></script>
You can now supply this DataSource to the components via the
setDataSource() method. The complete code for a page that binds a
grid and form to this DataSource is:
DataSource contactsDS = DataSource.get("contacts");
Version 2.3
21
Visual Components Smart GWT Quick Start
In this example, the grid and form components are now automatically
generating component fields based on DataSource fields. Note that the
form has chosen specific controls for certain fields—it does so based on
the following rules:
You can override these choices by setting the editorType attribute on the
<field> tag in the .ds.xml file to the Java classname of the desired
FormItem.
Property Values
name Unique field identifier (required on every
DataSource field)
type ―text‖ | ―integer‖ | ―float‖ | ―boolean‖ | ―date‖ |
―sequence‖
title Default user-visible label for the field.
length Maximum length of text value in characters.
hidden Defaults to true; specifies whether this field
should be hidden from the end user. When
hidden, it will not appear in the default
presentation, and it will not appear in any field
selectors (such as the column picker menu in a
ListGrid).
detail Defaults to true; specifies whether this field is a
―detail‖ that should not be shown by default in
multi-record summary views such as a ListGrid.
required ―true‖ | ―false‖; applies validation on both client
and server to verify that the field is non-blank.
valueMap An array of values, or an object containing
storedValue:displayValue pairs.
editorType FormItem class to use when editing this field (in
any DataBoundComponent).
22 Version 2.3
Smart GWT Quick Start Visual Components
com.smartgwt.client.docs.serverds
Version 2.3
23
Visual Components Smart GWT Quick Start
By default, a component with both fields and a DataSource will only show
the fields defined on the component, in the order they are defined on the
component. To change this behavior, use
setUseAllDataSourceFields(true). Now, all DataSource fields will be
shown unless you provide a component field definition where you have
called setHidden(true).
DataSource Operations
Smart GWT provides a standardized set of data operations that act upon
DataSources:
24 Version 2.3
Smart GWT Quick Start Visual Components
You may call any of these four methods directly on a DataSource object or
on a databound ListGrid or TreeGrid.
For example, the following code saves a new Record to the contactDS
DataSource and displays a confirmation when the save completes:
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSResponse;
contactDS.addData(contact,callback);
Version 2.3
25
Visual Components Smart GWT Quick Start
Method Description
editRecord() Starts editing an existing record
editNewRecord() Starts editing a new record
saveData() Saves the current edits (add new
records; update existing records)
Convenience Method
listGrid.removeSelectedData()
dynamicForm.editSelectedData(listGrid)
detailViewer.viewSelectedData(listGrid)
Each sample in the samples directory in the SDK shows the most
common DataBoundComponents interacting with DataSources.
26 Version 2.3
Smart GWT Quick Start Visual Components
Version 2.3
27
Visual Components Smart GWT Quick Start
6. Layout
Component Layout
Most of the code snippets seen so far create just one or two visual
components, and position them manually with the left, top, width, and
height properties.
This manual layout approach becomes brittle and complex with more
components. For example, you may want to:
Smart GWT includes a set of layout managers to provide these and other
automatic behaviors. The Smart GWT layout managers implement
consistent dynamic sizing, positioning, and reflow behaviors that cannot
be accomplished with HTML and CSS alone.
28 Version 2.3
Smart GWT Quick Start Visual Components
Member Description
property
layoutAlign Alignment with respect to the breadth axis
of the layout (―left,‖ ―right,‖ ―top,‖ ―bottom,‖
or ―center‖).
showResizeBar Specifies whether a drag-resize bar appears
between this component and the next
member in the layout. (―true‖ | ―false‖).
width, height Layout-managed components support a ―*‖
value (in addition to the usual number and
percentage values) for their size on the
length axis of the layout, to indicate that
they should take a share of the remaining
space after fixed-size components have been
counted (this is the default behavior if no
width/height is specified).
Version 2.3
29
Visual Components Smart GWT Quick Start
You can use the special LayoutSpacer component to insert extra space into
your layouts. For example, here is the code to create a basic page header
layout, with a left-aligned logo and right-aligned title:
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
Container Components
30 Version 2.3
Smart GWT Quick Start Visual Components
Form Layout
When form controls appear in a DynamicForm, their positions and sizes are
controlled by the Smart GWT form layout manager. The form layout
manager generates a layout structure similar to an HTML table. Form
controls and their titles are rendered in a grid from left-to-right, top-to-
bottom. You can configure the high-level structure of this grid with the
following DynamicForm properties:
DynamicForm Description
property
numCols Total number of columns in the grid, for form
controls and their titles. Set to a multiple of 2,
to allow for titles, so numCols:2 allows one
form control per row and numCols:4 allows
two form controls per row.
titleWidth Number of pixels allocated to each title
column in the layout.
colWidths Optional array of pixel widths for all columns
in the form. If specified, these widths will
override the column widths calculated by the
form layout manager.
You can control the positioning and sizing of form controls in the layout
grid by changing their positions in the fields array, their height and width
properties, and the following field properties:
Field Description
property
colSpan Number of form layout columns occupied by this
control (not counting its title, which occupies
another column)
rowSpan Number of form layout rows occupied by this
control
startRow Specifies whether this control should always start
a new row. (―true‖ | ―false‖)
endRow Specifies whether this control should always end
its row. (―true‖ | ―false‖)
Version 2.3
31
Visual Components Smart GWT Quick Start
Field Description
property
showTitle Specifies whether this control should display its
title. (―true‖ | ―false‖)
align Horizontal alignment of this control within its
area of the form layout grid (―left,‖ ―right,‖ or
―center‖)
You can also use the following special form items to include extra space
and formatting elements in your form layouts:
HeaderItem
BlurbItem
SpacerItem
RowSpacerItem
See the JavaDoc for these classes for properties that can be set for
additional control.
com.smartgwt.client.docs.FormLayout
com.smartgwt.client.widgets.form.fields.FormItem
32 Version 2.3
Smart GWT Quick Start Visual Components
7. Data Integration
DataSource Requests
Version 2.3
33
Visual Components Smart GWT Quick Start
Path 1 makes use of the Smart GWT Server Framework. Available with
Pro edition and above, the server framework is a set of Java libraries and
servlets that can be integrated with any pre-existing Java application.
Unless you are forced to use a different approach (for example, you are
not using a Java-based server, and cannot deploy a Java-based server in
front of your existing server), it is highly recommended that you use the
Smart GWT Server Framework for data integration. The server
framework delivers an immense range of functionality that compliments
any existing application and persistence engine. Chapter 8, Smart GWT
Server Framework, provides an overview.
If you cannot use the Smart GWT Server Framework, the best approaches
for data integration are covered later in this chapter.
34 Version 2.3
Smart GWT Quick Start Visual Components
Regardless of the data integration approach used, the data in the request
and response objects has the same meaning.
data: the search criteria (for ―fetch‖), new record values (―add‖ or
―update‖) or criteria for the records to delete (―remove‖)
errors: for a validation error response, fields that were invalid and
error messages for each
If you are using the Smart GWT Server Framework with one of the built-
in DataSource types (such as SQL or JPA/Hibernate), you will not need to
do any request or response transformation work and can proceed directly
to Chapter 8, Smart GWT Server Framework.
If you cannot use the server framework, but you are free to define the
format and content of messages passed between the browser and your
server, the simplest data integration approach is the RestDataSource class.
Version 2.3
35
Visual Components Smart GWT Quick Start
If, instead, you are required to integrate with a pre-existing service that
defines its own HTTP-based protocol, you can configure a subclass of the
DataSource class to customize the HTTP request format and the expected
format of responses.
For services that return XML or JSON data (including WSDL), you can
specify XPath expressions indicating what part of the data should be
transformed into dsResponse.data. If XPath expressions are not sufficient,
you can override DataSource.transformRequest() and
DataSource.transformResponse() and add Java code to handle those
cases.
com.smartgwt.client.data.RestDataSource
com.smartgwt.client.docs.ClientDataIntegration
showcase/#featured_restfulds
36 Version 2.3
Smart GWT Quick Start Visual Components
However, Smart GWT does not require that a data provider implement all
of these capabilities. In fact, Smart GWT is able to use a ―flat file‖ as a
response to the ―fetch‖ operation, and implement searching and sorting
behaviors within the browser.
com.smartgwt.client.data.ResultSet
com.smartgwt.client.data.DataSource#cacheAllData
Version 2.3
37
Visual Components Smart GWT Quick Start
38 Version 2.3
Smart GWT Quick Start Visual Components
Do not protect the static resources that are part of the skin
or the SmartClient runtime underlying Smart GWT,
specifically the URL patterns sc/skins/* and sc/system/*.
These are publically available files; protecting them just
causes a performance hit and in some cases can negatively
affect caching
If you are using the Smart GWT Server Framework, see the Declarative
Security section of Chapter 8 for further authentication and authorization
features, including the ability to declare role-based security restrictions in
.ds.xml file, create variations on DataSource operations accessible to
different user roles, and create certain operations accessible to
unauthenticated users.
Relogin
When a user‘s session has expired and the user tries to navigate to a
protected resource, typical authentication systems will redirect the user to
a login page. With Ajax systems such as Smart GWT, this attempted
redirect may happen in response to background data operations, such as a
form trying to save. In this case, the form perceives the login page as a
malformed response and displays a warning, and the login page is never
displayed to the user.
The ideal handling of this scenario is that the form‘s attempt to save is
―suspended‖ while the user re-authenticates, then is completed normally.
Smart GWT makes it easy to implement this ideal handling through the
Relogin subsystem.
com.smartgwt.client.docs.Relogin
Version 2.3
39
Visual Components Smart GWT Quick Start
The Smart GWT server framework is a set of Java libraries and servlets
that can be integrated with any pre-existing Java application.
The server framework allows you to rapidly connect Smart GWT visual
components to pre-existing Java business logic, or can provide complete,
pre-built persistence functionality based on SQL, Hibernate, JPA or other
Java persistence frameworks.
DataSource Generation
As an example, if you had the Java Bean Contact, the following is a valid
DataSource whose fields would be derived from a Java Bean:
<DataSource ID="contacts" schemaBean="com.sample.Contact"/>
The following DataSource would derive its fields from your database
columns (as well as being capable of all CRUD operations):
<DataSource ID="contacts" serverType="sql"
tableName="contacts" autoDeriveSchema="true" />
40 Version 2.3
Smart GWT Quick Start Visual Components
The default rules for mapping between Java and SQL types and
DataSourceField types are summarized in the following table:
Version 2.3
41
Visual Components Smart GWT Quick Start
For example, you may have a database column employment that stores a
one-character employment status code, and needs a valueMap to display
appropriate values to end users:
<DataSource ID="contacts" serverType="sql"
tableName="contacts" autoDeriveSchema="true">
<fields>
<field name="employment">
<valueMap>
<value ID="E">Employed</value>
<value ID="U">Unemployed</value>
</valueMap>
</field>
</fields>
</DataSource>
com.smartgwt.client.docs.serverds.DataSource.schemaBean
com.smartgwt.client.docs.serverds.DataSource.autoDeriveSchema
com.smartgwt.client.docs.serverds.DataSource.inheritsFrom
42 Version 2.3
Smart GWT Quick Start Visual Components
When using the Smart GWT server framework, DSRequests go through the
following flow:
If you cannot use one of the built-in DataSource types (perhaps you have
a pre-existing, custom ORM solution, or perhaps persistence involves
contacting a remote server), you will also have Java code to implement
persistence operations.
Version 2.3
43
Visual Components Smart GWT Quick Start
As your application grows, you can add Java logic or take over processing
at any point in the standard server flow. For example, you can:
com.smartgwt.client.docs.ServerDataIntegration
44 Version 2.3
Smart GWT Quick Start Visual Components
DMI (Direct Method Invocation) allows you to declare what Java class
and method should be invoked when specific DSRequests arrive at the
server. A DMI is declared by adding a <serverObject> tag to your
DataSource descriptor.
For example, the following declaration indicates that all DSRequests for
this DataSource should go to the Java class com.sample.DMIHandler:
<DataSource ID="contacts" schemaBean="com.sample.Contact">
<serverObject className="com.sample.DMIHandler"/>
</DataSource>
com.smartgwt.client.docs.serverds.ServerObject
Version 2.3
45
Visual Components Smart GWT Quick Start
DMI Parameters
Methods invoked via DMI can simply declare arguments of certain types,
and they are provided automatically.
When this method is called via DMI, it will be passed the current
DSRequest. If the method also needs the current HttpServletRequest, it
can simply be declared as an additional parameter:
public DSResponse fetch(DSRequest dsRequest, HttpServletRequest request) {
This works for all of the common objects available to a servlet (such as
HttpSession) as well as all Smart GWT objects involved in DSRequest
processing (such as DataSource).
com.smartgwt.client.docs.DMIOverview
A DMI can directly perform the required persistence operation and return
a DSResponse populated with data, and in some use cases, this is the right
approach.
However, if you are using one of the built-in DataSource types in Smart
GWT, or you build a similar, re-usable DataSource of your own, DMI can
be used to perform business logic that modifies the default behavior of
DataSources.
46 Version 2.3
Smart GWT Quick Start Visual Components
For example, you might add criteria to a ―fetch‖ request so that users
who are not administrators cannot see records that are marked
deleted.
if (!servletRequest.isUserInRole("admin")) {
dsRequest.setFieldValue("deleted", "false");
}
For this kind of error, the default client-side behavior will be to show
the error in the UI component where saving was attempted.
For this kind of error, the default client-side behavior is a dialog box
shown to the user, with the message ―Failure‖ in this case. Customize
this via the client-side API RPCManager.setHandleErrorCallback().
Version 2.3
47
Visual Components Smart GWT Quick Start
Note that many of the DMI use cases described above can alternatively be
achieved by adding simple declarations to your DataSource .ds.xml file—
this is covered in more detail in the upcoming Operation Bindings
section.
com.isomorphic.datasource.DSRequest
com.isomorphic.datasource.DSResponse
com.smartgwt.client.rpc.RPCManager
com.smartgwt.client.widgets.form.DynamicForm
smartgwtee/showcase/#sql_user_specific_data
48 Version 2.3
Smart GWT Quick Start Visual Components
Returning Data
Whether you return data via DMI, via a custom DataSource, or via writing
your own servlet and directly working with the RPCManager class, data that
should be delivered to the browser is passed to the dsResponse.setData()
API.
This API can accept a wide variety of common Java objects and
automatically translate them into Record objects. For example, if you are
responding to a fetch, the followingJava will all translate to a List of
Records if passed to setData().
Each Map becomes a Record and each key/value pair in each Map
becomes a Record attribute.
Any Collection of Java Beans, that is, Java Objects that use the
Java getPropertyName() / setPropertyName() naming convention
In contrast, with Smart GWT, the list of fields in your DataSource is the
full list of fields used by UI components, so it serves as a natural
definition of what data to serialize, eliminating the need to define a
redundant ―DTO.‖
Version 2.3
49
Visual Components Smart GWT Quick Start
Note that when delivering data to the browser, the Smart GWT server
framework does not attempt to re-create Java Objects of the same type as
the objects you supply to the server side setData() API. Systems such as
GWT-RPC, which do attempt this, tend to require a huge amount of
scaffolding code to be written in order to enable a comparatively trivial
amount of functional code to be shared.
For the rare case of logic that can run unchanged on client and server, we
recommend creating a small library of static methods and including it in
both client and server-side projects.
com.isomorphic.js.JSTranslater.toJS()
50 Version 2.3
Smart GWT Quick Start Visual Components
This means that if any DataSource can support the ―update‖ operation,
the DataSource also supports batch editing of records in a ListGrid with
no additional code, since this just involves executing the ―update‖
operation multiple times. Likewise, in other instances in which
components automatically use queuing (such as removeSelectedData()
with multiple records selected, and multi-row drag and drop)
implementing singular DataSource operations means that batch
operations work automatically without additional effort.
com.isomorphic.rpc.RPCManager.setTransactionPolicy()
When the client receives the response for an entire queue, each response
is processed in order, including any callbacks passed to DataBound
Component methods.
com.smartgwt.rpc.RPCManager.startQueue()
Version 2.3
51
Visual Components Smart GWT Quick Start
com.isomorphic.servlet.RESTHandler
Operation Bindings
52 Version 2.3
Smart GWT Quick Start Visual Components
These are both operations of type ―fetch‖ on the same DataSource, and
they can be distinguished by adding an operationId to the Operation
Binding. For example, if you had written a DMI method that performs full
text search called ―doFullTextSearch,‖ you could declare an
operationBinding like this:
<operationBinding operationType="fetch" operationId="fullTextSearch">
<serverObject className="com.sample.DMIHandler"
methodName="doFullTextSearch"/>
</operationBinding>
You could now configure a ListGrid to use this Operation Binding via
grid.setFetchOperation("doFullTextSearch").
Version 2.3
53
Visual Components Smart GWT Quick Start
Setting outputs always limits the fields that are sent to the browser,
regardless of the type of DataSource used. With the built-in DataSources,
it also limits the fields requested from the underlying data store. Custom
DataSources or DMIs that want to similarly optimize communication with
the datastore can detect the requested outputs via
dsRequest.getOutputs().
com.smartgwt.client.docs.serverds.OperationBinding
Declarative Security
54 Version 2.3
Smart GWT Quick Start Visual Components
By default, the Declarative Security system uses the core servlets API
httpServletRequest.isUserInRole() to determine whether the user has a
given role. In most J2EE security or JAAS security frameworks you might
use, this API functions properly, and Declarative Security requires no
setup steps – just start adding requiresRole attributes.
com.smartgwt.client.docs.serverds.OperationBinding.
requiresRole
com.isomorphic.rpc.RPCManager.setUserRoles()
com.isomorphic.servlet IDACall
Version 2.3
55
Visual Components Smart GWT Quick Start
com.smartgwt.client.docs.serverds.DataSource.
requiresAuthentication
com.isomorphic.rpc.RPCManager.setAuthenticated()
com.isomorphic.servlet IDACall
In many places within the DataSource .ds.xml file, you can provide
a dynamic expression to be evaluated on the server.
References to objects in the template context have a prefix of ‗$‘, and dot
notation is used to access any property for which a standard Java Bean
―getter‖ method exists, or to access any value in a java.util.Map by its
key. For example, $httpSession.id retrieves the current sessionId via
HttpSession.getId(), and $dsRequest.criteria.myFieldName will retrieve
a criteria value for the field ―myFieldName‖ via DSRequest.getCriteria(),
which returns a Map.
56 Version 2.3
Smart GWT Quick Start Visual Components
Server-Assigned Criteria/Values
Version 2.3
57
Visual Components Smart GWT Quick Start
Mail Templates
SQL/HQL Templating
The Velocity template language can also call Java methods, create new
variables, even execute conditional logic or iterate over collections. To
take full advantage of Velocity‘s advanced capabilities, you can extend the
power of dynamic expressions by adding additional data or objects to the
Velocity context.
com.smartgwt.client.docs.serverds.VelocitySupport
com.smartgwt.client.docs.serverds.Validator.serverCondition
com.isomorphic.datasource.DSRequest.addToTemplateContext()
velocity.apache.org/user-guide
58 Version 2.3
Smart GWT Quick Start Visual Components
SQL Templating
When using the SQLDataSource with the Power Edition of Smart GWT,
SQL Templating enables fine-grained customization of generated SQL.
The SQL generator in Power Edition can take the DSRequests generated by
DataBound components and automatically handle:
When you inevitably have to customize the generated SQL for a particular
use case, it‘s critical to preserve as much of this powerful, automatic
behavior as possible.
In contrast, the SQL Templating system lets you change small parts of the
generated SQL while leaving all the difficult, database-specific SQL up to
Smart GWT. SQL Templating also allows you to take advantage of
database-specific features where appropriate, without losing automatic
SQL generation for standard features.
Version 2.3
59
Visual Components Smart GWT Quick Start
The following table summarizes the SQL statements that are generated
and how the DSRequest is used (note, these aren‘t the actual statements –
additional SQL exists to handle data paging and database-specific quirks):
60 Version 2.3
Smart GWT Quick Start Visual Components
com.smartgwt.client.docs.CustomQuerying
Version 2.3
61
Visual Components Smart GWT Quick Start
A customized query can return additional fields that aren‘t part of the
DataSource‘s primary table, and even allow criteria to be automatically
applied to such fields.
For the common case of incorporating a field from another table, declare
a field as usual with a <field> tag, then add the attribute
tableName="otherTable". Setting tableName enables a field to be fetched
from another table and used in the WHERE clause, but automatically
excludes the field from the SQL for any operationType except ―fetch.‖
For example, given the orderItem and stockItem tables from the
preceding example, imagine stockItem had a column itemName that you
want to include in results from the orderItem DataSource.
<DataSource ID="orderItem" serverType="sql" tableName="orderItem"
autoDeriveSchema="true">
<fields>
<field name="itemName" type="text" tableName="stockItem"/>
</fields>
<operationBinding operationType="fetch">
<tableClause>orderItem, stockItem</tableClause>
<whereClause>orderItem.stockItem_id == stockItem.id AND
($defaultWhereClause)
</whereClause>
</operationBinding>
</DataSource>
This approach can be extended to any number of fields from other tables.
smartgwtee/showcase/#large_valuemap_sql
62 Version 2.3
Smart GWT Quick Start Visual Components
In some cases, you may have several different Operation Bindings that use
different sets of added fields. In this case, you can set customSQL="true"
on the <field> element to turn off automatic generation. Then, use the
following <operationBinding> properties to control whether SQL is
generated for the field on a per-<operationBinding> basis.
Setting Meaning
customValueFields Comma-separated list of fields to allow in SELECT
clause despite being customSQL="true"
customCriteriaFields Comma-separated list of fields to allow in WHERE
clause despite being customSQL="true"
excludeCriteriaFields Comma-separated list of fields to exclude from
$defaultWhereClause
You can also define custom SQL on a per-field basis rather than a per-
clause basis using the following properties on a <field>:
Setting Meaning
customSelectExpression Expression to use in SELECT and WHERE clauses
customUpdateExpression Expression to use in SET clause of UPDATE
customInsertExpression Expression to use in VALUES clause of INSERT.
Defaults to customUpdateExpression
Version 2.3
63
Visual Components Smart GWT Quick Start
com.smartgwt.client.docs.serverds.DataSourceField.customSQL
com.smartgwt.client.docs.serverds.OperationBinding.
customCriteriaFields
com.smartgwt.client.docs.serverds.DataSourceField.
customSelectExpression
com.smartgwt.client.docs.serverds.DataSourceField.
sqlStorageStrategy
smartgwtee/showcase/#sql_dynamic_reporting
Declarative
Centralized
64 Version 2.3
Smart GWT Quick Start Visual Components
Secure
Custom DataSources
You can create a DataSource that calls existing business logic by simply
using DMI to declare what Java method to call for each operation. This is
a good approach if you have only a few DataSources, or while you are still
learning the basics.
Version 2.3
65
Visual Components Smart GWT Quick Start
You can also add custom attributes to your DataSource .ds.xml file.
The APIs DataSource.getProperty() and DSField.getProperty()
allow you to detect added attributes at the DataSource and
DataSourceField level respectively. Use these attributes to configure
your persistence behavior (for example, the URL of a remove service
to contact) or use them to control additional features you add to the
built-in persistent DataSources.
com.smartgwt.client.docs.WriteCustomDataSource
66 Version 2.3
Smart GWT Quick Start Visual Components
New Components
The three most common approaches to build a new Smart GWT visual
component are:
Many of Smart GWT built-in components are built in this fashion, for
example, the Window class is a subclass of Layout that automatically
creates header, footer and body components.
Version 2.3
67
Visual Components Smart GWT Quick Start
Use this approach if your custom component does not resemble any of
the built-in layout classes (or any combination of nested layouts). The
Slider control included with Smart GWT is a good example of this
pattern: a Slider is created out of a Canvas parent, StretchImg track
element, and draggable Img thumb element. By reusing foundation
components, you avoid browser inconsistencies in HTML and CSS
rendering, event handling, and other areas.
3. Create a Canvas subclass that contains your own HTML and CSS
template code.
68 Version 2.3
Smart GWT Quick Start Visual Components
Switching Theme
Themes allow you to change the overall look-and-feel of your Smart GWT
user interface. You can ―re-skin‖ an application to match corporate
branding, to adhere to usability guidelines, or even to personalize look &
feel to individual user preferences.
Smart GWT includes several default themes. To get a visual preview of the
default themes, use the online Showcase, which includes a control to
dynamically switch themes.
Note: Smart GWT Pro/EE starter projects include .gwt.xml files that
inherit a single GWT module in order to include all Smart GWT
components in the project. For example, in the evaluation SDK, you‘ll see:
<inherits name="com.smartgwtee.SmartGwtEE"/>
This <inherits> tag implicitly includes a theme for the Smart GWT
components. Before adding a new <inherits> tag for a different theme,
add NoTheme to the end of the name attribute, like so:
<inherits name="com.smartgwtee.SmartGwtEENoTheme"/>
This revised <inherits> tag includes just the Smart GWT components,
with no theme.
Version 2.3
69
Visual Components Smart GWT Quick Start
Customizing Themes
In the previous section we looked at how to find and browse the default
themes. In each theme you will find a public folder with 3 sets of
resources:
Resource Contains
skin_styles.css a collection of CSS styles that are applied to
parts of visual components in various states
(e.g. cellSelectedOver for a selected cell in
a grid with mouse-over highlighting)
images a collection of small images that are used as
parts of visual components when CSS
styling is not sufficient (e.g.
TreeGrid/folder_closed.gif)
load_skin.js high-level programmatic styling (e.g.
listGrid.alternateRecordStyles) and sizes
for fixed-size elements (e.g.
window.edgeSize)
The best way to create a custom skin is to copy an existing skin that most
closely matches your intended look and feel and modify it. For example,
let‘s say you wanted to customize the built-in ―Enterprise‖ skin and call
the resulting skin ―BrushedMetal.‖ The procedure is as follows:
1. Use any .zip-compatible tool to unzip the .jar file and copy the
entire contents of the ―Enterprise‖ skin into a new folder called
―BrushedMetal.‖
2. Edit the load_skin.js file. Find the line near the top of the
file that reads:
isc.Page.setSkinDir("[ISOMORPHIC]/skins/Enterprise/")
70 Version 2.3
Smart GWT Quick Start Visual Components
5. Create a .jar for the skin. Eliminate the outer directory structure
com/smartclient/theme and replace with
com/mycompany/theme. Use any .zip-compatible tool to
create the .jar file, and add it to your Smart GWT project.
Version 2.3
71
Visual Components Smart GWT Quick Start
10. Tips
Beginner Tips
Architecture Tips
72 Version 2.3
Smart GWT Quick Start Visual Components
However, you should never place GWT widgets within a Smart GWT
container that is in turn within a GWT container. Until interoperability
standards emerge, intermixing widgets in this way is considered
unsupported usage, and any issue reports resulting from such usage will
not be considered bugs.
To reclaim all memory for a component that you no longer need, call
destroy() on it, then allow it to be garbage collected by removing all
references to it as usual. Note that destroy() is permanent, and once
you have called destroy() on a component, calling any other API is
expected to fail. Destroying a parent component automatically destroys
all children.
To reclaim some memory from a component that you wish to reuse later,
call clear(). This removes all HTML rendered by the component and
its children. You can call draw() to recreate the component‘s HTML later.
Frames essentially embed another instance of the web browser inside the
current web page. That instance behaves more like an independent
browser window than an integrated page component. Smart GWT‘s
dynamic components and background communication system allow you
to perform fully integrated partial-page updates, eliminating the need for
frames in most cases. If you must use frames, you should explicitly clear
them with frame.document.write("") when the parent page is unloaded,
to avoid memory leaks in Internet Explorer.
Version 2.3
73
Visual Components Smart GWT Quick Start
Smart GWT uses HTML and CSS elements as the ―pixels‖ for rendering a
complex user interface in the browser. It is technically possible to access
these elements directly from the browser DOM (Document Object Model).
However, these structures vary by browser type, version, and mode, and
they are regularly improved and optimized in new releases of Smart GWT.
The only stable, supported way to manipulate a Smart GWT component is
through its published interfaces.
74 Version 2.3
Smart GWT Quick Start Visual Components
This chapter offers advice for the most effective approaches to use when
evaluating Smart GWT for use in your project or product.
Smart GWT comes in several editions, including a free edition under the
Lesser GNU Public License (LGPL).
Version 2.3
75
Visual Components Smart GWT Quick Start
In contrast, if you were to evaluate using the LGPL edition and implement
REST-based integration, upon purchasing a license you will immediately
want to switch to the more powerful, pre-built server integration instead,
which also provides access to all server-based features. In this scenario
you will have wasted time building a REST connector during evaluation
and given yourself a false perception of the learning curve and effort
involved in using Smart GWT.
Evaluating Performance
Unlike many web sites, web applications are visited repeatedly by the
same users on a frequent basis, and users will spend significant time
actually using the application.
For example, in many different types of applications a user will search for
a specific record, view the details of that record, modify that record or
related data, and repeat this pattern many times within a given session.
76 Version 2.3
Smart GWT Quick Start Visual Components
With the correct performance testing approach in hand, you are ready to
correctly assess the performance of Smart GWT. If you have followed
Smart GWT best practices, you application will show a drastic reduction
in dynamic requests due to features like:
DataSource.cacheAllData documentation
Version 2.3
77
Visual Components Smart GWT Quick Start
forums.smartclient.com
78 Version 2.3
Smart GWT Quick Start Visual Components
Consider, for example, the long term cost of recreating any single feature
from the Pro product:
The price of the most advanced Smart GWT technology is a tiny part of
the overall cost of developing an application, and can deliver huge savings
in all of these areas. For this reason, it makes sense to work with the most
advanced Smart GWT technology available.
If you are a developer and you recognize that the features in Pro could
save you time, you may find that an argument firmly based on cost
savings and ROI (Return On Investment) will enable you to work with
cutting edge technology and save you from wasting time ―re-inventing the
wheel.‖
Version 2.3
79
Visual Components Smart GWT Quick Start
The free, open source (LGPL) version of Smart GWT exists because of the
commercial version of the product. The free and commercial parts of the
product are split in such a way that further development of the
commercial version necessarily involves substantial upgrades to the open
source version, and historically, new releases have contained as least as
many new features in the free product as in the commercial version.
As with any open source project, patches and contributions are always
welcome. However, as a professionally employed developer, the best way
to support the free product is to fuel further innovation by purchasing
licenses, support, and other services.
80 Version 2.3
Smart GWT Quick Start Visual Components
Contacts
Web www.smartclient.com
General info@smartclient.com
feedback@smartclient.com
Licensing sales@smartclient.com
Services services@smartclient.com
We welcome your feedback, and thank you for choosing Smart GWT.
End of Guide
Version 2.3
81