Getting Response through GWT using Http Protocol

Introduction

This article deals with getting the response from the server side using Google Web ToolKit Framework and Ajax. Google Web ToolKit is one of the Ajax frameworks which is mainly aimed at Java Developers.The main advantage of GWT is that it comes with a compiler which will translate the Java code written by the developers to highly optimized , browser independent Java Script, thereby eliminating the need of front-end developers to know Java.

In this article, we will see how to use GWT to send a HTTPRequest to the server and update the response on the client side using Ajax.Please find below the screenshot of the sample output.

In this example, we have a html file(HttpRequest.html) with a simple button. We shall be coding for the button and the other UI elements using GWT and not HTML.When the user clicks on the button, we shall be sending a httpRequest to “Response.html”.We shall also be updating “HttpRequest.html” with the content of “Response.html” through Ajax. In this article, we shall be seeing how to do all this using GWT.

Software Requirements

  • JDK 1.6
  • Eclipse 3.6 IDE
  • GWT SDK 1.7
  • GWT Eclipse Plug-in

File Structure

Please find below the File Structure of the application. The following are the files that are to be coded:

  • HttpRequest.java
  • HttpRequest.html
  • Response.html
  • HttpRequest.gwt.xml

Let’s try to understand the File Structure. The GWT web application will have src folder which has 3 packages.

In our case, we have

  • com.enr
  • com.enr.client
  • com.enr.server

com.enr package will have the file “HttpRequest.gwt.xml “. This is a configuration file which will be discussed more in detail later.

com.enr.client package will have the client side related files. The files that are to be converted into javascript will have to be placed here.

com.enr.server package will have the server related files, for example the servlet code etc. All the java classes that need not be converted to Java Script will have to be placed here.

An another important folder will be war which has WEB-INF folder. war folder is the one wherein all the GWT-compiler generated files will be placed.

Now let us add in code into HttpRequest.java

HttpRequest.java

This is the file, wherein, we will be coding for the front end. We shall be using GWT packages to generate UI Elements like button , label etc. The code that is present in “HttpRequest.java” will be converted to html and JavaScript by the GWT Compiler.The generated javascript code will be encapsulated into a iframe(invisible frame) and will be pasted into “HttpRequest.html”. This code will run on the browser.

Soon after the user clicks on the button, as discussed before, we need to generate a HttpRequest and also update the page with the response. Let’s try to understand how to do the same using GWT.

In order to generate a HttpRequest we need to use RequestBuilder class. RequestBuilder is a builder class which is used to generate HttpRequest Objects .This builder is however limited to build GET or POST requests.We use the method sendRequest to send the request to the specified url.In our case since we are sending the request to “Response.html”, the url should be corresponding to “Response.html”

We need to use RequestCallback class which will be invoked on recieving the response.

The RequestCallback class has two methods, onError and OnResponseRecieved which will be invoked upon getting the response depending on whether the response is positive or negative.These methods get references of the request and response objects which can be used to update the html page with the response.

In our example, we shall be sending the request on the click of the button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.enr.client;
 
	import com.google.gwt.core.client.EntryPoint;
	import com.google.gwt.core.client.GWT;
	import com.google.gwt.event.dom.client.ClickEvent;
	import com.google.gwt.event.dom.client.ClickHandler;
	import com.google.gwt.event.dom.client.KeyCodes;
	import com.google.gwt.event.dom.client.KeyUpEvent;
	import com.google.gwt.event.dom.client.KeyUpHandler;
	import com.google.gwt.http.client.Request;
	import com.google.gwt.http.client.RequestBuilder;
	import com.google.gwt.http.client.RequestCallback;
	import com.google.gwt.http.client.RequestException;
	import com.google.gwt.http.client.RequestTimeoutException;
	import com.google.gwt.user.client.Window;
	import com.google.gwt.user.client.rpc.AsyncCallback;
	import com.google.gwt.user.client.ui.Button;
	import com.google.gwt.user.client.ui.DialogBox;
	import com.google.gwt.user.client.ui.HTML;
	import com.google.gwt.user.client.ui.Label;
	import com.google.gwt.user.client.ui.RootPanel;
	import com.google.gwt.user.client.ui.TextBox;
	import com.google.gwt.user.client.ui.VerticalPanel;
	import com.google.gwt.http.client.Response;
	/**
	 * Entry point classes define onModuleLoad().
	 */
	public class HttpRequest implements EntryPoint {
 
		public static final int STATUS_CODE_OK = 200;
 
 
		public static void doGet(String url) {
			RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
 
			try {
				Request response = builder.sendRequest(null, new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						if (exception instanceof RequestTimeoutException) {
							Window.alert("The request has timed out");
						} else {
	        			Window.alert(exception.getMessage());
						}
					}
					public void onResponseReceived(Request request, Response response) {
						if (STATUS_CODE_OK == response.getStatusCode()) {
							HTML responseLabel=new HTML("<h3>Response is gonna be updated here</H3>");
							responseLabel.setHTML(response.getText());
							responseLabel.addStyleName("response");
							RootPanel.get().add(responseLabel);
						} else {
							Window.alert(""+response.getStatusCode());
						}
					}
				});
			} catch (RequestException e) {
				// Code omitted for clarity
			}
		}
 
		public void onModuleLoad() {
			Button button=new Button("Get Response");
			button.addClickHandler(new ClickHandler(){
				@Override
				public void onClick(ClickEvent event) {
					doGet("Response.html");
				}
			});
			RootPanel.get("container").add(button);
		}	
	}

HttpRequest.gwt.xml

This is a configuration file which has information about the name of the module and entry point class and various GWT java packages that needs to be imported by the web application.

Entry point class is the class that will be executed on running the application.

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.1//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.1/distro-source/core/src/gwt-module.dtd">
	<module rename-to='httprequest'>
		<inherits name='com.google.gwt.user.User'/>
		<inherits name='com.google.gwt.user.theme.standard.Standard'/>
		<inherits name="com.google.gwt.http.HTTP"/>
		<entry-point class='com.enr.client.HttpRequest'/>
	</module>

HttpRequest.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<link type="text/css" rel="stylesheet" href="HttpRequest.css">
		<title>Web Application Starter Project</title>
		<script type="text/javascript" language="javascript" src="httprequest/httprequest.nocache.js"></script>
		<style>
			.response
			{
				background-color: #efefef;
				padding-bottom: 1.5em; 
			}
		</style>
	</head>
	<body>
		<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
		<h1>Getting the response through Ajax using HTTP Protocol</h1>
		<center><div id="container"></div></center>
	</body>
	</html>

Response.html

1
2
3
4
5
6
7
8
<html>
	<head>
		<title>Response</title>
	</head>
	<body>
		<h2>This is the response through GWT Http Ajax</h2>
	</body>
	</html>

Conclusion

In this article , we have seen the usage of RequestBuilder Class and RequestCallback class to send in a HttpRequest and update the page with server side response through Ajax.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*