63
Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 1

Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Advanced Web Technology5) Google Web Toolkits -GWT, Client Side

Emmanuel BenoistSpring Term 2020

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 1

Page 2: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Table of Contents� Presentation of GWT

� Hello World Application

� WidgetsHello World

� Event Handling

� Applying Style Sheets

� Deployment

� InternationalizationStatic String i18n

� Remote Procedure Code

� JSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 2

Page 3: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Presentation of GWT

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 3

Page 4: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Motivation

What is GWT?A development environment in pure Java for rich webapplicationsProvides Java for programming both client and server sides

Advantages of GWTHomogenous environmentTesting of a web application (using JUnit)

Not integrated in JSFConcurent system developed by google

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 4

Page 5: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Principle

Write Java codeUse Java on Server SideBut also on a Client SideCommunication is handeled conveniently

Tests in a JVMTesting is done using JUnitPlugin in the browserTests are conducted inside one JVM (based on Java Code)

Compile into JavascriptCreates different versions for different browsersEach browser receives only the “right” versionCan be deployed on Java ServersOr any other server (if the server part is not Java)

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 5

Page 6: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Hello World Application

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 6

Page 7: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Hello World Application

Download the GWTFrom Google Code Web sitehttp://code.google.com

Create an applicationExecute./webAppCreator -out /home/bie1/test/ ch.bfh.awt.HelloA default application is createdIncludes ant and Eclipse project files

Test the ApplicationGo to the directoryexecute ant devmodeInstall the plugin in your browserTest the application

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 7

Page 8: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Directories created

Source files: /src/Package for client side application :/src/ch/bfh/awt/clientServer side classes : /src/ch/bfh/awt/serverThe file /src/ch/bfh/awt/Hello.gwt.xml contains theconfigurations for the GWT application

Web Application: /war/Contains html, css, javascript, gifs, and the likeContains the WEB-INF/ directory (where the server classes areautomatically compiledThe directory /war/ will receive the JavaScript files compiledfrom the client applicationAt the end the content of this directory is copied to the server

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 8

Page 9: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Widgets

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 9

Page 10: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Hello World

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 10

Page 11: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Hello WorldHello.html: contains a real HTML

Containing layout,References to images, JavaScript, CSS

Reference to the script loading the files

<script type="text/javascript" language="javascript" src="↘

→hello/hello.nocache.js"></script>

And it contains place-holders that will be manipulatedfrom “Java”.

<div id="nameFieldContainer"></div><div id="sendButtonContainer"></div><div style="color:blue;" id="responseContainer"↘

→></div>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 11

Page 12: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

HTML FIle<!doctype html><html><head><meta http−equiv="content−type" content="text/html;␣charset=UTF↘

→−8"><link type="text/css" rel="stylesheet" href="Hello.css"><title>Web Application Starter Project</title><script type="text/javascript" language="javascript" src="hello/hello.↘→nocache.js"></script></head><body>...

<h1>Web Application Starter Project</h1>

Please enter your name:<div id="nameFieldContainer"></div><div id="sendButtonContainer"></div><div style="color:blue;" id="responseContainer"></div>

</body></html>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 12

Page 13: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Java File

Contains the definition of the user interfaceDefinition of the Widgets used,Panels,Text fields,buttons

Extends the EntryPoint classDefines the onModuleLoad() function.

Defines the Event HandlingDefines functions to be executed when an Event is fired.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 13

Page 14: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Hello.javapackage ch.bfh.awt.client;import ........../∗∗ Entry point classes define <code>onModuleLoad()</code>.↘→ ∗/public class Hello implements EntryPoint {public void onModuleLoad() {

final Button sendButton = new Button("Send");final TextBox nameField = new TextBox();final Label responseLabel = new Label();RootPanel.get("nameFieldContainer").add(nameField);RootPanel.get("sendButtonContainer").add(sendButton);RootPanel.get("responseContainer").add(responseLabel);nameField.setFocus(true);... // Event Handling}

}Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 14

Page 15: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Widgets

List of default widgetsButtons: Button, PushButton, RadioButton,CheckBox,,,Calendar: DatePickerLists : ListBox , CellList,Trees: MenuBar, Tree with CellTree,Panels: PopoupPanel, StackPanel, HorizontalPanel,VerticalPanel,http://code.google.com/intl/fr-FR/webtoolkit/doc/latest/RefWidgetGallery.html

Possibility to write your own widgets:http://code.google.com/intl/en/webtoolkit/doc/latest/DevGuideUiCustomWidgets.htmlComposite components (composition of existing components)or from scratch in Java code

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 15

Page 16: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Example: StockWatcher1An interface to watch stock values

Presentation (when deployed on localhost)localhost:8080/stockWatcherGWT

User Interface: One pageOne pageA list containing the stocksA field to type the stock intoA button to add a new stock

Back-officeNo back-office todayCommunications with the servers are seen in the next courseCommunication available:

I Remote Procedure Call (RPC) in JavaI Call to JSON data on the same server (PHP for instance)I Call to JSON data on another server (against the same origin

policy).1Source:http:

//code.google.com/intl/fr-FR/webtoolkit/doc/latest/tutorial/Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 16

Page 17: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

The HTML Page 2

<body><img src="images/bfh.jpg" /><h1>Stock Watcher testing project</h1><div id="stockList"></div><iframe src="javascript:’’" id="__gwt_historyFrame" tabIndex=’↘→−1’ style="position:absolute;width:0;height:0;border:0"></iframe><noscript><div style="width:␣22em;␣position:␣absolute;␣left:␣50%;␣margin−left↘→:␣−11em;␣color:␣red;␣background−color:␣white;␣border:␣1px␣solid␣↘→red;␣padding:␣4px;␣font−family:␣sans−serif">Your web browser must have JavaScript enabledin order for this application to display correctly.

</div></noscript>

</body>

2/war/StockWatcher.htmlBerner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 17

Page 18: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Java Files 3

Contains WidgetsmainPanel a vertical panel containing componentsaddPanel an horizontal panel containing a textbox and abuttonstocksFlexTable a fexible table containing lines and columnsnewSymbolTextBox a text box to enter text intoaddStockButton a button that generates an event whenclicked onlastUpdatedLabel a label contains a text

private VerticalPanel mainPanel = new VerticalPanel();private FlexTable stocksFlexTable = new FlexTable();private HorizontalPanel addPanel = new HorizontalPanel();private TextBox newSymbolTextBox = new TextBox();private Button addStockButton = new Button("Add");private Label lastUpdatedLabel = new Label();3/src/ch/bfh/awt/client/StockWatcher.java

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 18

Page 19: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

The Java Filepublic void onModuleLoad() {

// Create table for stock data.stocksFlexTable.setText(0, 0, "Symbol");stocksFlexTable.setText(0, 1, "Price");stocksFlexTable.setText(0, 2, "Change");stocksFlexTable.setText(0, 3, "Remove");// Assemble Add Stock panel.addPanel.add(newSymbolTextBox);addPanel.add(addStockButton);// Assemble Main panel.mainPanel.add(stocksFlexTable);mainPanel.add(addPanel);mainPanel.add(lastUpdatedLabel);// Associate the Main panel with the HTML host page.RootPanel.get("stockList").add(mainPanel);// Move cursor focus to the input box.newSymbolTextBox.setFocus(true);

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 19

Page 20: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Event Handling

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 20

Page 21: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Event Handling

Events Handlers are attached to widgetsEvents in GWT use the event handler interface model similarto other user interface frameworks.To subscribe to an event, you pass a particular event handlerinterface to the appropriate widget.An event handler interface defines one or more methods thatthe widget then calls to announce (publish) an event.

Example: Hello WorldAdd an event handler for a click on the buttonAdd an event handler when a user types on the Enter key

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 21

Page 22: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Event Handlers for Hello World 4

class MyHandler implements ClickHandler, KeyUpHandler {public void onClick(ClickEvent event) {

copyName();}public void onKeyUp(KeyUpEvent event) {

if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {copyName();

}}private void copyName() {String textToCopy = nameField.getText();responseLabel.setText(textToCopy);

}}MyHandler handler = new MyHandler();sendButton.addClickHandler(handler);nameField.addKeyUpHandler(handler);

4Inside the definition of the class HelloBerner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 22

Page 23: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Event Handling by Stock Watcher// Listen for mouse events on the Add button.addStockButton.addClickHandler(new ClickHandler() {public void onClick(ClickEvent event) {addStock();

}});// Listen for keyboard events in the input box.newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {public void onKeyPress(KeyPressEvent event) {if (event.getCharCode() == KeyCodes.KEY_ENTER) {addStock();

}}

});}private void addStock() {

// TODO Auto−generated method stub}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 23

Page 24: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Manipulate the content of theWidgets

Java can generate an alert().

Window.alert("’" + symbol + "’␣is␣not␣a␣valid␣symbol.");

One can manipulate elements in a list

int removedIndex = stocks.indexOf(symbol);stocks.remove(removedIndex);stocksFlexTable.removeRow(removedIndex + 1);

Or change the text of a label or a text box

private void copyName() {// First, we validate the input.String textToCopy = nameField.getText();responseLabel.setText(textToCopy);

}

or

// Display timestamp showing last refresh.lastUpdatedLabel.setText("Last␣update␣:␣"+ DateTimeFormat.getMediumDateTimeFormat().↘→format(new Date()));

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 24

Page 25: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Applying Style Sheets

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 25

Page 26: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Applying Style SheetsConfigure the standard theme

standard.css : contains the GWT default styles (themes)In GWT config file : Hello.gwt.xmlDefines the theme:

<inherits name=’com.google.gwt.user.theme.standard.↘→Standard’/><!−− <inherits name="com.google.gwt.user.theme.↘→chrome.Chrome"/> −−><!−− <inherits name="com.google.gwt.user.theme.dark.↘→Dark"/> −−>

Associate a CSS fileHello.css : contains the project specific classesLinked inside the Hello.html

<link type="text/css" rel="stylesheet" href="Hello.css">

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 26

Page 27: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Add Style to the elements

Suppose we have the following style:

/∗ stock list header row ∗/.watchListHeader {background−color: #2062B8;color: white;font−style: italic;

}/∗ stock list flex table ∗/.watchList {border: 1px solid silver;padding: 2px;margin−bottom:6px;

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 27

Page 28: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Add Style to the elements (Cont.)We add style to the elements of the first row of the table

// Add styles to elements in the stock list table.stocksFlexTable.getRowFormatter().addStyleName(0, "↘

→watchListHeader");

Format all the elements of a table

stocksFlexTable.addStyleName("watchList");

Or format only one cell

stocksFlexTable.getCellFormatter().addStyleName(0, 1, "↘

→watchListNumericColumn");

Or even a panel

addPanel.addStyleName("addPanel");

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 28

Page 29: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Deployment

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 29

Page 30: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Deployment

Compile the application into JavaScriptUsing GWT Compile Project button in EclipseOr executing ant build

Compilation writes all the required files in the Wardirectory

Uses the definition files and all the existing files in the war/(html, gif, images, css, . . . )

Copy the content of the directoryTo a servlet engine if you use the server side functionalityTo any server if using only the client side

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 30

Page 31: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Internationalization

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 31

Page 32: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Internationalization : I18N ModuleCore types related to internationalization:

LocaleInfo Provides information about the current locale.

Constants Useful for localizing typed constant values

Messages Useful for localizing messages requiring arguments

ConstantsWithLookup Like Constants but with extra lookupflexibility for highly data-driven applications

Dictionary Useful when adding a GWT module to existinglocalized web pages

Localizable Useful for localizing algorithms encapsulated ina class or when the classes above don’t provide sufficientcontrol

DateTimeFormat Formatting dates as strings. See the sectionon date and number formatting.

NumberFormat Formatting numbers as strings. See thesection on date and number formatting.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 32

Page 33: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Static String i18n

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 33

Page 34: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Interantionalizing StringsImplement the Constant Interface

Contains only static stringsVery efficient and compiled once.

Implement the Messages InterfaceAllows to insert values in the stringFor instance numbers or datesEquivalent to the resource bundle in applications.

Dynamic String InternationalizationThe Dictionary class lets your GWT application consumestrings supplied by the host HTML page.Convenient if your existing web server has a localizationsystem that you do not wish to integrate with the static stringinternationalization methods.

Implement the Localizable InterfaceThe most powerful techniqueallows you to go beyond simple string substitutioncreate localized versions of custom types.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 34

Page 35: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Implement the Constants Interface

Create the StockWatcherConstants interfaceUses annotations for the default translationImplements the Constant interface (GWT)Bound automatically to theStockWatcherConstants*.properties files

The java file must contain one method for each of theconstants in the properties files

The right value is found at runtime, corresponding to the locale

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 35

Page 36: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Example: the Constants filepackage com.google.gwt.sample.stockwatcher.client;import com.google.gwt.i18n.client.Constants;public interface StockWatcherConstants extends Constants {@DefaultStringValue("StockWatcher")String stockWatcher();@DefaultStringValue("Symbol")String symbol();@DefaultStringValue("Price")String price();@DefaultStringValue("Change")String change();@DefaultStringValue("Remove")String remove();@DefaultStringValue("Add")String add();

}Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 36

Page 37: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Translate it to German

Create a file StockWatcherConstants_de.properties

stockWatcher = Aktienbeobachtersymbol = Symbolprice = Kurschange = Änderungremove = Entfernenadd = Hinzufügen

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 37

Page 38: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Implement the Messages interface

For Strings containing informationSimilar to resource bundles in JavaCan contain strings with parameters

’’{0}’’ ist kein gültiges Aktiensymbol.

The number is a place holder

myString = First parm is {0}, second parm is {1}, third ↘

→parm is {2}.

Usefull for integrating dates, prices, internationalizedresults

I Usefull but less efficient. The strings must be produced atruntime

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 38

Page 39: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Messages filepackage com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.i18n.client.Messages;

import java.util.Date;

public interface StockWatcherMessages extends Messages {@DefaultMessage("’’{0}’’␣is␣not␣a␣valid␣symbol.")String invalidSymbol(String symbol);

@DefaultMessage("Last␣update:␣{0,date,medium}␣{0,time,↘→medium}")String lastUpdate(Date timestamp);

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 39

Page 40: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

The corresponding properties file

StockWatcherMessages_de.properties file.

lastUpdate = Letzte Aktualisierung: {0,date,medium} {0,time,↘→medium}invalidSymbol = ’’{0}’’ ist kein gültiges Aktiensymbol.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 40

Page 41: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Replace content

Replace the texts with place holders

<body><img src="images/GoogleCode.png"/><h1 id="appTitle"></h1>

Replacing strings set programmaticallyCreate the instances of the classes (internationalized)

private ArrayList<String> stocks = new ArrayList<String>();private StockWatcherConstants constants = GWT.create(↘→StockWatcherConstants.class);private StockWatcherMessages messages = GWT.create(↘→StockWatcherMessages.class);

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 41

Page 42: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Replace content (Cont)

Set the content:

// Set the window title, the header text, and the Add button ↘

→text.Window.setTitle(constants.stockWatcher());RootPanel.get("appTitle").add(new Label(constants.↘→stockWatcher()));addStockButton = new Button(constants.add());// Create table for stock data.stocksFlexTable.setText(0, 0, constants.symbol());stocksFlexTable.setText(0, 1, constants.price());stocksFlexTable.setText(0, 2, constants.change());stocksFlexTable.setText(0, 3, constants.remove());

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 42

Page 43: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Add a supported locale:

Inside StockWatcher.gwt.xml add the property

<entry−point class=’com.google.gwt.sample.stockwatcher↘→.client.StockWatcher’/>

<extend−property name="locale" values="de"/></module>

Load the german version by adding &locale=de

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 43

Page 44: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Client Server Communication

Remote Procedure CodeFrom Java To JavaSupported by the languageOptimized and easy to test

JSONFor communicating with the same server

JSONPFor cross server communicationOvergoes the Same Origin Policy

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 44

Page 45: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Remote Procedure Code

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 45

Page 46: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

GWT Remote Procedure CallRPC contains:

the service that runs on the serverthe method you are calling

the client code that invokes the servicethe Java data objects that pass between the client andserver

Both (client and server) must serialize and deserialize theobjects

You need to write three componentsDefine the interface StockPriceService that extendsRemoteService and lists all your RPC methodsCreate a class StockPriceServiceImpl that extendsRemoteServiceServlet and implements the interface youcreated above.Define an asynchronous interface StockPriceServiceAsyncto your service to be called from the client-side code.

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 46

Page 47: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

GWT Remote Procedure Call5

5Source: code.google.comBerner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 47

Page 48: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

StockPriceService interfaceIn the packagecom.google.gwt.sample.stockwatcher.client

package com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.user.client.rpc.RemoteService;import com.google.gwt.user.client.rpc.RemoteServiceRelativePath↘

→;

@RemoteServiceRelativePath("stockPrices")public interface StockPriceService extends RemoteService {

StockPrice[] getPrices(String[] symbols);}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 48

Page 49: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

StockPriceServiceImpl classpackage com.google.gwt.sample.stockwatcher.server;import com.google.gwt.sample.stockwatcher.client.StockPrice;import com.google.gwt.sample.stockwatcher.client.StockPriceService;import com.google.gwt.user.server.rpc.RemoteServiceServlet;import java.util.Random;public class StockPriceServiceImpl extends RemoteServiceServlet implements↘→ StockPriceService {private static final double MAX_PRICE = 100.0; // $100.00private static final double MAX_PRICE_CHANGE = 0.02; // +/− 2%public StockPrice[] getPrices(String[] symbols) {Random rnd = new Random();StockPrice[] prices = new StockPrice[symbols.length];for (int i=0; i<symbols.length; i++) {double price = rnd.nextDouble() ∗ MAX_PRICE;double change = price ∗ MAX_PRICE_CHANGE ∗ (rnd.nextDouble↘→() ∗ 2f − 1f);prices[i] = new StockPrice(symbols[i], price, change);

}return prices;

}}Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 49

Page 50: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Include the server-side code in theGWT moduleDefine new servlets in the web.xml

<web−app><welcome−file−list>

<welcome−file>StockWatcher.html</welcome−file></welcome−file−list><servlet>

<servlet−name>stockPriceServiceImpl</servlet−name><servlet−class>com.google.gwt.sample.stockwatcher.server.↘→StockPriceServiceImpl</servlet−class>

</servlet><servlet−mapping><servlet−name>stockPriceServiceImpl</servlet−name><url−pattern>/stockwatcher/stockPrices</url−pattern>

</servlet−mapping></web−app>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 50

Page 51: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Invoking the service from the client

Making asynchronous calls to the server

package com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface StockPriceServiceAsync {

void getPrices(String[] symbols, AsyncCallback<StockPrice[]> ↘

→callback);

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 51

Page 52: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Making the remote procedure callprivate void refreshWatchList() {

// Initialize the service proxy.if (stockPriceSvc == null) {stockPriceSvc = GWT.create(StockPriceService.class);

}// Set up the callback object.AsyncCallback<StockPrice[]> callback = new AsyncCallback<↘

→StockPrice[]>() {public void onFailure(Throwable caught) {

// TODO: Do something with errors.}public void onSuccess(StockPrice[] result) {updateTable(result);

}};// Make the call to the stock price service.stockPriceSvc.getPrices(stocks.toArray(new String[0]), callback);

}Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 52

Page 53: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Serializing Java objects

GWT RPC requires that all service method parametersand return types be serializable.

package com.google.gwt.sample.stockwatcher.client;

import java.io.Serializable;

public class StockPrice implements Serializable {

private String symbol;private double price;private double change;

...

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 53

Page 54: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

JSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 54

Page 55: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Retrieving JSON DataJSON stands for JavaScript Object Notation

Language independant formatVery light

Example

[{"symbol": "ABC","price": 87.86,"change": −0.41

},{"symbol": "DEF","price": 62.79,"change": 0.49

}]

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 55

Page 56: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Server part

JSON can be generated by a servlet

out.println("␣␣{");out.print("␣␣␣␣\"symbol\":␣\"");out.print(stockSymbol);out.println("\",");out.print("␣␣␣␣\"price\":␣");out.print(price);out.println(’,’);out.print("␣␣␣␣\"change\":␣");out.println(change);out.println("␣␣},");

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 56

Page 57: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

JSON generated by PHP<?phpheader(’Content−Type:␣text/javascript’);define("MAX_PRICE", 100.0); // $100.00define("MAX_PRICE_CHANGE", 0.02); // +/− 2%echo ’[’;$q = trim($_GET[’q’]);if ($q) {$symbols = explode(’␣’, $q);for ($i=0; $i<count($symbols); $i++) {$price = lcg_value() ∗ MAX_PRICE;$change = $price ∗ MAX_PRICE_CHANGE ∗ (lcg_value() ∗ 2.0 − ↘

→1.0);echo ’{’;echo "\"symbol\":\"$symbols[$i]\",";echo "\"price\":$price,";echo "\"change\":$change";echo ’}’;if ($i < (count($symbols) − 1)) {echo ’,’;

}}

}echo ’]’;

?>

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 57

Page 58: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Transform JSON object intoJavaScript

use the built in JavaScript function evalThe function will receive a response.getText() as aparameter

private final native JsArray<StockData> asArrayOfStockData(↘→String json) /∗−{

return eval(json);}−∗/;

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 58

Page 59: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Manipulate JSON objects

Create a JavaScriptObject StockData to manipulate the data input inJava

package com.google.gwt.sample.stockwatcher.client;import com.google.gwt.core.client.JavaScriptObject;class StockData extends JavaScriptObject {

// Overlay types always have protected, zero argument constructors.protected StockData() {}// JSNI methods to get stock data.public final native String getSymbol() /∗−{ return this.symbol; }−∗/;public final native double getPrice() /∗−{ return this.price; }−∗/;public final native double getChange() /∗−{ return this.change; }−∗/;// Non−JSNI method to return change percentage.public final double getChangePercent() {return 100.0 ∗ getChange() / getPrice();

}}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 59

Page 60: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Connect the Web serverPrepare the list of stocks

private void refreshWatchList() {if (stocks.size() == 0) {return;

}String url = JSON_URL;// Append watch list stock symbols to query URL.Iterator iter = stocks.iterator();while (iter.hasNext()) {url += iter.next();if (iter.hasNext()) {url += "+";

}}url = URL.encode(url);// TODO Send request to server and handle errors.

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 60

Page 61: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

Connect the Web Server (Cont.)// Send request to server and catch any errors.

RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);try {Request request = builder.sendRequest(null, new RequestCallback() {public void onError(Request request, Throwable exception) {displayError("Couldn’t␣retrieve␣JSON");

}public void onResponseReceived(Request request, Response response↘→) {if (200 == response.getStatusCode()) {updateTable(asArrayOfStockData(response.getText()));

} else {displayError("Couldn’t␣retrieve␣JSON␣(" + response.↘→getStatusText()

+ ")"); } } });} catch (RequestException e) {displayError("Couldn’t␣retrieve␣JSON");

}

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 61

Page 62: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

ConclusionGWT: pure Java Web Application

Client and Server share one languageTesting made easy

Testing of Web Application is often a nightmareJUnit testing is possibleDebugging inside one JVM : In Eclipse or in devmode

Security?What is executed where?What is transfered and can be manipulated?What is tested where?

Useful featuresI18NClient Server CommunicationRemote Procedure CallJSON

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 62

Page 63: Advanced Web Technology 5) Google Web Toolkits - GWT ... · Advanced Web Technology 5) Google Web Toolkits - GWT, Client Side Emmanuel Benoist Spring Term 2020 Berner Fachhochschule

References

Tutorial by Google Code http://code.google.com/intl/fr-FR/webtoolkit/overview.htmlhttp://code.google.com/intl/fr-FR/webtoolkit/doc/latest/tutorial/gettingstarted.html

Developer Guide by Google Codehttp://code.google.com/intl/fr-FR/webtoolkit/doc/latest/DevGuide.html

Hello World ExampleObtained by executing the create application script.

Tutorial for Client Server communicationhttp://code.google.com/intl/fr-FR/webtoolkit/doc/latest/tutorial/clientserver.html

Berner Fachhochschule | Haute école spécialisée bernoise | Berne University of Applied Sciences 63