SlideShare a Scribd company logo
GWT Training – Session III

Communicating with the
Server

Snehal Masne
www.TechProceed.com
Contents



Asynchronous HTTP Request
Submitting Data using HTML Form





Traditional
GWT

GWT RPC

www.TechProceed.com
Asynchronous HTTP Requests
/ /create a new GET request
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/info.php”);
try{
//send the request
builder.sendRequest( null, new RequestCallback() {
public void onError(Request request, Throwable exception){
//log the error
}
public void onResponseReceived(Request request, Response response){
//process response
}
});
}
catch (RequestException e){
//handle request exception
}
www.TechProceed.com
Asynchronous HTTP Requests
– cont'd




builder.sendRequest() method receives a
string data to be sent with the request and
RequestCallback object that handles the
response from the server
null is passed if there is no data to be sent to
the data

www.TechProceed.com
Submitting Data to Server Using
HTML Form
<form name="input" action="register.php" method="post">
Username: <input type="text" name="user"><br/>
Email: <input type="text" name="email"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="Submit">
</form>

Data Submitted
POST /register.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=Faiz&email=faizbash%40gmail.com&password=secret

www.TechProceed.com
GWT Equivalent for Form Data Submission Constructing HTTP Request Manually
//build the data to post
StringBuffer postBuilder = new StringBuffer();
postBuilder.append("username=" );
postBuilder.append( URL.encodeComponent( username ) );
postBuilder.append("&email=" );
postBuilder.append( URL.encodeComponent( email ) );
postBuilder.append("&password=" );
postBuilder.append( URL.encodeComponent( password ) );
try{
//create and submit the request
RequestBuilder requestBuilder = new RequestBuilder( RequestBuilder.POST,
GWT.getModuleBaseURL()+"/register.php" );
requestBuilder.sendRequest( postBuilder.toString(), new RequestCallback(){
public void onError(Request request, Throwable exception){
// handle error
}
public void onResponseReceived(Request request, Response response){
// handle response
}
});
}catch( Exception e){ // handle exception }
www.TechProceed.com
GWT Equivalent for Form Data Submission
– Using FormPanel
//create the form panel, set its action and method
final FormPanel form = new FormPanel();
form.setAction("/register.php");
form.setMethod(FormPanel.METHOD_POST);

//set the main widget for the panel to a vertical panel
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
//create the username field
TextBox tb = new TextBox();
tb.setName("username");
panel.add(tb);
//create the e-mail field
TextBox tb = new TextBox();
tb.setName("email ");
panel.add(tb);

www.TechProceed.com
GWT Equivalent for Form Data Submission
– Using FormPanel (cont'd)‫‏‬
//create the password field
PasswordTextBox ptb = new PasswordTextBox();
ptb.setName("password");
panel.add(ptb);
//create the Submit button
Button submit = new Button(“Submit”);
submit.addClickHandler( new ClickHandler() {
public void onClick(Widget sender) {
form.submit();
}
});
//add submit button to panel
panel.add(submit);

www.TechProceed.com
GWT RPC








GWT extends a browser’s capability to asynchronously
communicate with the server by providing a remote procedure call
(RPC) library.
Calls to the server are simplified by providing you with an
interface of methods that can be called similarly to regular method
calls.
GWT marshal the calls (convert to a stream of data) and send to
the remote server.
At the server side, the data, is un-marshalled the method on the
server is invoked

www.TechProceed.com
GWT RPC – cont'd




In GWT, the RPC library is divided into two packages:
 com.google.gwt.user.client.rpc package used for clientside RPC support
 com.google.gwt.user.server.rpc package used for serverside RPC support The client side provides interfaces that
you can use to tag
When the client code is compiled to Javascript using the
GWT compiler, the code required to do the RPC marshaling
will be generated

www.TechProceed.com
GWT RPC Implementation


To understand how GWT RPC works, we
would implement the data form submission
using it

www.TechProceed.com
GWT RPC Implementation – Step 1


Create the RPC interface (stub) on the client side
 Create a new interface named LoginService under the
my.utm.kase.gwttraining.client package
 Edit the code to look like the one below:
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("login")
public interface LoginService extends RemoteService {
boolean login(String username, String email, String password);
}


Add the following in /war/WEB-INF/web.xml

www.TechProceed.com
GWT RPC Implementation – Step 2


Configure the servlet


Add the following in /war/WEB-INF/web.xml
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>
my.utm.kase.gettraining.server.LoginServiceImpl
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/gwttraining/login</url-pattern>
</servlet-mapping>

www.TechProceed.com
GWT RPC Implementation – Step 3


Create an async counterpart interface of the LoginService. This interface
defines the callback method that will be called when the server generates
a response
 Create another interface, LoginServiceAsync under
my.utm.kase.gwttraining.client package
 Edit the code to look like the one below:
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface LoginServiceAsync {
boolean login(String username, String email,
String password, AsyncCallback<Boolean> callback);
}


The async method always returns void and takes parameters similar
to its stub counterpart plus an AsyncCallback parameter which
specifies the return value of the stub method which is Void in this case
www.TechProceed.com
GWT RPC Implementation – Step 4


Implement the remote method on the server side
 Create a class, LoginServiceImpl under my.utm.kase.gwttraining.server
package
 Edit the code to look like the one below:
import my.utm.kase.gwttraining.client.LoginService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class LoginServiceImpl extends RemoteServiceServlet implements
LoginService {
public boolean login(String username, String email, String password)

{
if( username.equals("faizbash") && password.equals("secret") )
{
return true;
}
else return false;
}
}
www.TechProceed.com
GWT RPC Implementation – Step 5


Call the remote method
 Create a login widget in my.utm.kase.gwttraining.client package to get
username, email and password from user. It also captures login event and
makes a RPC to loign user.
public class LoginWidget extends Composite {
public LoginWidget() {
//login panel
FlexTable loginTable = new FlexTable();
final TextBox usernameBox = new TextBox();
final TextBox emailBox = new TextBox();
final PasswordTextBox passwordBox = new PasswordTextBox();
Button loginButton = new Button("Login");
loginButton.addClickHandler( new ClickHandler() {
public void onClick(ClickEvent event) {
login(usernameBox.getText(), emailBox.getText(), passwordBox.getText();
}
});
//username widget
loginTable.setWidget(0, 0, new Label("Username"));
loginTable.setWidget(0, 1, usernameBox);
//email widget
loginTable.setWidget(1, 0, new Label("Email"));
loginTable.setWidget(1, 1, emailBox);

www.TechProceed.com
GWT RPC Implementation –
Step 5 (cont'd)‫‏‬
//password widget
loginTable.setWidget(2, 0, new Label("Password"));
loginTable.setWidget(2, 1, passwordBox);
//login button widget
loginTable.setWidget(3, 0, loginButton);
loginTable.getFlexCellFormatter().setColSpan(3, 0, 2);
//init loginTable
initWidget(loginTable);
}
public void login(String username, String email, String password) {
//create a callback method
AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) {
//handle failure
Window.alert("Failed to login");
}
public void onSuccess(Boolean status) {
if( status )
Window.alert("Login successful");
else
Window.alert("Invalid username or passord");
}
};

www.TechProceed.com
GWT RPC Implementation –
Step 5 (cont'd)‫‏‬
//Create a remote service proxy to talk to the server-side Greeting service.
final LoginServiceAsync loginService = GWT.create(LoginService.class);
//invoke the remote method
loginService.login(username, email, password, callback);
}
}



Instantiate the widget in the GWTTrainingWidgets entry point class:
//login widget
LoginWidget loginWidget = new LoginWidget();
tabPanel.add(loginWidget, "Login");



Run or refresh to test

www.TechProceed.com
Thank you

www.TechProceed.com

More Related Content

PPTX
WCF - In a Week
PDF
Statying Alive - Online and OFfline
PPT
JSON Rules Language
PPTX
Maintaining Your Code Clint Eastwood Style
PPT
ODP
Building Websocket Applications with GlassFish and Grizzly
PDF
Android dev 3
ODP
Testing RESTful Webservices using the REST-assured framework
WCF - In a Week
Statying Alive - Online and OFfline
JSON Rules Language
Maintaining Your Code Clint Eastwood Style
Building Websocket Applications with GlassFish and Grizzly
Android dev 3
Testing RESTful Webservices using the REST-assured framework

What's hot (18)

ODP
Implementing Comet using PHP
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
PDF
Mobile web performance - MoDev East
PDF
Pushing the Web: Interesting things to Know
PDF
Web II - 02 - How ASP.NET Works
PDF
Asynchronous web apps with the Play Framework 2.0
PPTX
Android and REST
PDF
MongoDB.local Berlin: App development in a Serverless World
PDF
HTTP 프로토콜의 이해와 활용
PDF
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
PPT
2310 b 11
PDF
EAI design patterns/best practices
PDF
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
PDF
Node.js cluster
PDF
Devoxx France: Fault tolerant microservices on the JVM with Cassandra
PPTX
Legacy Dependency Kata v2.0
PPTX
Legacy Code Kata v3.0
PPTX
I/O Extended (GDG Bogor) - Sidiq Permana
Implementing Comet using PHP
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Mobile web performance - MoDev East
Pushing the Web: Interesting things to Know
Web II - 02 - How ASP.NET Works
Asynchronous web apps with the Play Framework 2.0
Android and REST
MongoDB.local Berlin: App development in a Serverless World
HTTP 프로토콜의 이해와 활용
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
2310 b 11
EAI design patterns/best practices
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
Node.js cluster
Devoxx France: Fault tolerant microservices on the JVM with Cassandra
Legacy Dependency Kata v2.0
Legacy Code Kata v3.0
I/O Extended (GDG Bogor) - Sidiq Permana
Ad

Viewers also liked (9)

PDF
聖徳ゼロテック株式会社 事業紹介
PPT
Algoritmos
PDF
Orsys - Cycle certifiant - Administrateur Reseaux
DOCX
Herramientas del sistema
PPTX
Caldentalinsurance
PPTX
Proyecto de vida
PDF
A/B Testing and MultiVariate Testing
PPTX
Rashid_Feroze_AState_2016_Poster
PPTX
Gli uomini del paleolitico
聖徳ゼロテック株式会社 事業紹介
Algoritmos
Orsys - Cycle certifiant - Administrateur Reseaux
Herramientas del sistema
Caldentalinsurance
Proyecto de vida
A/B Testing and MultiVariate Testing
Rashid_Feroze_AState_2016_Poster
Gli uomini del paleolitico
Ad

Similar to GWT training session 3 (20)

PPT
GWT Training - Session 3/3
PPTX
Gwt session
PPTX
Gwt session
PPT
Gwt and rpc use 2007 1
PPT
Google Web Toolkits
PPT
Google Web Toolkit Introduction - eXo Platform SEA
PDF
GWT - developing web applications with java (script) - Ewa Maciaś
PPT
GWT
PDF
Introduction to Google Web Toolkit
PDF
Google Web Toolkitのすすめ
PDF
GWT - Building Rich Internet Applications Using OO Tools
PPT
GWT_Framework
PPTX
GWT = easy AJAX
PPT
Google Web Toolkits
PPT
Gooogle Web Toolkit
PPT
PPT
PPT
Intro on GWT & Google APIs (Vikram Rangnekar, COO of Socialwok.com)
PPTX
Google web toolkit ( Gwt )
PPT
Gwt RPC
GWT Training - Session 3/3
Gwt session
Gwt session
Gwt and rpc use 2007 1
Google Web Toolkits
Google Web Toolkit Introduction - eXo Platform SEA
GWT - developing web applications with java (script) - Ewa Maciaś
GWT
Introduction to Google Web Toolkit
Google Web Toolkitのすすめ
GWT - Building Rich Internet Applications Using OO Tools
GWT_Framework
GWT = easy AJAX
Google Web Toolkits
Gooogle Web Toolkit
Intro on GWT & Google APIs (Vikram Rangnekar, COO of Socialwok.com)
Google web toolkit ( Gwt )
Gwt RPC

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25 Week I
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation_ Review paper, used for researhc scholars
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation
Understanding_Digital_Forensics_Presentation.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Dropbox Q2 2025 Financial Results & Investor Presentation
Chapter 3 Spatial Domain Image Processing.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Network Security Unit 5.pdf for BCA BBA.
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

GWT training session 3

  • 1. GWT Training – Session III Communicating with the Server Snehal Masne www.TechProceed.com
  • 2. Contents   Asynchronous HTTP Request Submitting Data using HTML Form    Traditional GWT GWT RPC www.TechProceed.com
  • 3. Asynchronous HTTP Requests / /create a new GET request RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/info.php”); try{ //send the request builder.sendRequest( null, new RequestCallback() { public void onError(Request request, Throwable exception){ //log the error } public void onResponseReceived(Request request, Response response){ //process response } }); } catch (RequestException e){ //handle request exception } www.TechProceed.com
  • 4. Asynchronous HTTP Requests – cont'd   builder.sendRequest() method receives a string data to be sent with the request and RequestCallback object that handles the response from the server null is passed if there is no data to be sent to the data www.TechProceed.com
  • 5. Submitting Data to Server Using HTML Form <form name="input" action="register.php" method="post"> Username: <input type="text" name="user"><br/> Email: <input type="text" name="email"><br/> Password: <input type="password" name="password"><br/> <input type="submit" value="Submit"> </form> Data Submitted POST /register.php HTTP/1.1 Content-Type: application/x-www-form-urlencoded username=Faiz&email=faizbash%40gmail.com&password=secret www.TechProceed.com
  • 6. GWT Equivalent for Form Data Submission Constructing HTTP Request Manually //build the data to post StringBuffer postBuilder = new StringBuffer(); postBuilder.append("username=" ); postBuilder.append( URL.encodeComponent( username ) ); postBuilder.append("&email=" ); postBuilder.append( URL.encodeComponent( email ) ); postBuilder.append("&password=" ); postBuilder.append( URL.encodeComponent( password ) ); try{ //create and submit the request RequestBuilder requestBuilder = new RequestBuilder( RequestBuilder.POST, GWT.getModuleBaseURL()+"/register.php" ); requestBuilder.sendRequest( postBuilder.toString(), new RequestCallback(){ public void onError(Request request, Throwable exception){ // handle error } public void onResponseReceived(Request request, Response response){ // handle response } }); }catch( Exception e){ // handle exception } www.TechProceed.com
  • 7. GWT Equivalent for Form Data Submission – Using FormPanel //create the form panel, set its action and method final FormPanel form = new FormPanel(); form.setAction("/register.php"); form.setMethod(FormPanel.METHOD_POST); //set the main widget for the panel to a vertical panel VerticalPanel panel = new VerticalPanel(); form.setWidget(panel); //create the username field TextBox tb = new TextBox(); tb.setName("username"); panel.add(tb); //create the e-mail field TextBox tb = new TextBox(); tb.setName("email "); panel.add(tb); www.TechProceed.com
  • 8. GWT Equivalent for Form Data Submission – Using FormPanel (cont'd)‫‏‬ //create the password field PasswordTextBox ptb = new PasswordTextBox(); ptb.setName("password"); panel.add(ptb); //create the Submit button Button submit = new Button(“Submit”); submit.addClickHandler( new ClickHandler() { public void onClick(Widget sender) { form.submit(); } }); //add submit button to panel panel.add(submit); www.TechProceed.com
  • 9. GWT RPC     GWT extends a browser’s capability to asynchronously communicate with the server by providing a remote procedure call (RPC) library. Calls to the server are simplified by providing you with an interface of methods that can be called similarly to regular method calls. GWT marshal the calls (convert to a stream of data) and send to the remote server. At the server side, the data, is un-marshalled the method on the server is invoked www.TechProceed.com
  • 10. GWT RPC – cont'd   In GWT, the RPC library is divided into two packages:  com.google.gwt.user.client.rpc package used for clientside RPC support  com.google.gwt.user.server.rpc package used for serverside RPC support The client side provides interfaces that you can use to tag When the client code is compiled to Javascript using the GWT compiler, the code required to do the RPC marshaling will be generated www.TechProceed.com
  • 11. GWT RPC Implementation  To understand how GWT RPC works, we would implement the data form submission using it www.TechProceed.com
  • 12. GWT RPC Implementation – Step 1  Create the RPC interface (stub) on the client side  Create a new interface named LoginService under the my.utm.kase.gwttraining.client package  Edit the code to look like the one below: import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("login") public interface LoginService extends RemoteService { boolean login(String username, String email, String password); }  Add the following in /war/WEB-INF/web.xml www.TechProceed.com
  • 13. GWT RPC Implementation – Step 2  Configure the servlet  Add the following in /war/WEB-INF/web.xml <servlet> <servlet-name>loginServlet</servlet-name> <servlet-class> my.utm.kase.gettraining.server.LoginServiceImpl </servlet-class> </servlet> <servlet-mapping> <servlet-name>loginServlet</servlet-name> <url-pattern>/gwttraining/login</url-pattern> </servlet-mapping> www.TechProceed.com
  • 14. GWT RPC Implementation – Step 3  Create an async counterpart interface of the LoginService. This interface defines the callback method that will be called when the server generates a response  Create another interface, LoginServiceAsync under my.utm.kase.gwttraining.client package  Edit the code to look like the one below: import com.google.gwt.user.client.rpc.AsyncCallback; public interface LoginServiceAsync { boolean login(String username, String email, String password, AsyncCallback<Boolean> callback); }  The async method always returns void and takes parameters similar to its stub counterpart plus an AsyncCallback parameter which specifies the return value of the stub method which is Void in this case www.TechProceed.com
  • 15. GWT RPC Implementation – Step 4  Implement the remote method on the server side  Create a class, LoginServiceImpl under my.utm.kase.gwttraining.server package  Edit the code to look like the one below: import my.utm.kase.gwttraining.client.LoginService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class LoginServiceImpl extends RemoteServiceServlet implements LoginService { public boolean login(String username, String email, String password) { if( username.equals("faizbash") && password.equals("secret") ) { return true; } else return false; } } www.TechProceed.com
  • 16. GWT RPC Implementation – Step 5  Call the remote method  Create a login widget in my.utm.kase.gwttraining.client package to get username, email and password from user. It also captures login event and makes a RPC to loign user. public class LoginWidget extends Composite { public LoginWidget() { //login panel FlexTable loginTable = new FlexTable(); final TextBox usernameBox = new TextBox(); final TextBox emailBox = new TextBox(); final PasswordTextBox passwordBox = new PasswordTextBox(); Button loginButton = new Button("Login"); loginButton.addClickHandler( new ClickHandler() { public void onClick(ClickEvent event) { login(usernameBox.getText(), emailBox.getText(), passwordBox.getText(); } }); //username widget loginTable.setWidget(0, 0, new Label("Username")); loginTable.setWidget(0, 1, usernameBox); //email widget loginTable.setWidget(1, 0, new Label("Email")); loginTable.setWidget(1, 1, emailBox); www.TechProceed.com
  • 17. GWT RPC Implementation – Step 5 (cont'd)‫‏‬ //password widget loginTable.setWidget(2, 0, new Label("Password")); loginTable.setWidget(2, 1, passwordBox); //login button widget loginTable.setWidget(3, 0, loginButton); loginTable.getFlexCellFormatter().setColSpan(3, 0, 2); //init loginTable initWidget(loginTable); } public void login(String username, String email, String password) { //create a callback method AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { public void onFailure(Throwable caught) { //handle failure Window.alert("Failed to login"); } public void onSuccess(Boolean status) { if( status ) Window.alert("Login successful"); else Window.alert("Invalid username or passord"); } }; www.TechProceed.com
  • 18. GWT RPC Implementation – Step 5 (cont'd)‫‏‬ //Create a remote service proxy to talk to the server-side Greeting service. final LoginServiceAsync loginService = GWT.create(LoginService.class); //invoke the remote method loginService.login(username, email, password, callback); } }  Instantiate the widget in the GWTTrainingWidgets entry point class: //login widget LoginWidget loginWidget = new LoginWidget(); tabPanel.add(loginWidget, "Login");  Run or refresh to test www.TechProceed.com