Tuesday, July 06, 2010

AjaxGWTExample

1) AjaxGWTExample : This example will give you usage of AJAX with GWT.

AjaxGWTExample.html:

doctype html>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

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

<title>Web Application Starter Projecttitle>

<script type="text/javascript" language="javascript" src="ajaxgwtexample/ajaxgwtexample.nocache.js">script>

<script type="text/javascript">

function loadXMLDoc()

{

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET","ajax_info.txt",true);

xmlhttp.send();

}

script>

head>

<body>

<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 enabled

in order for this application to display correctly.

div>

noscript>

<h1>Web Application Starter Projecth1>

<table align="center">

<tr>

<td colspan="2" style="font-weight:bold;">Please enter your name:td>

tr>

<tr>

<td id="nameFieldContainer">td>

<td id="sendButtonContainer">td>

tr>

<tr>

<td colspan="2" style="color:red;" id="errorLabelContainer">td>

tr>

table>

<div id="myDiv"><h2>Let AJAX comes with GWT this texth2>div>

<button type="button" onclick="loadXMLDoc()">Change Contentbutton>

body>

html>

ajax_info.txt:

This is test of AJAX.

Web.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>greetServletservlet-name>

<servlet-class>ajaxGWTExample.server.GreetingServiceImplservlet-class>

servlet>

<servlet-mapping>

<servlet-name>greetServletservlet-name>

<url-pattern>/ajaxgwtexample/greeturl-pattern>

servlet-mapping>

<welcome-file-list>

<welcome-file>AjaxGWTExample.htmlwelcome-file>

welcome-file-list>

web-app>

AjaxGWTExample.gwt.xml:

xml version="1.0" encoding="UTF-8"?>

<module rename-to='ajaxgwtexample'>

<inherits name='com.google.gwt.user.User'/>

<inherits name='com.google.gwt.user.theme.standard.Standard'/>

<entry-point class='ajaxGWTExample.client.AjaxGWTExample'/>

<source path='client'/>

<source path='shared'/>

module>

AjaxGWTExample:

package ajaxGWTExample.client;

import ajaxGWTExample.shared.FieldVerifier;

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.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;

/**

* Entry point classes define onModuleLoad().

*/

public class AjaxGWTExample implements EntryPoint {

/**

* The message displayed to the user when the server cannot be reached or

* returns an error.

*/

private static final String SERVER_ERROR = "An error occurred while "

+ "attempting to contact the server. Please check your network "

+ "connection and try again.";

/**

* Create a remote service proxy to talk to the server-side Greeting service.

*/

private final GreetingServiceAsync greetingService = GWT

.create(GreetingService.class);

/**

* This is the entry point method.

*/

public void onModuleLoad() {

final Button sendButton = new Button("Send");

final TextBox nameField = new TextBox();

nameField.setText("GWT User");

final Label errorLabel = new Label();

// We can add style names to widgets

sendButton.addStyleName("sendButton");

// Add the nameField and sendButton to the RootPanel

// Use RootPanel.get() to get the entire body element

RootPanel.get("nameFieldContainer").add(nameField);

RootPanel.get("sendButtonContainer").add(sendButton);

RootPanel.get("errorLabelContainer").add(errorLabel);

// Focus the cursor on the name field when the app loads

nameField.setFocus(true);

nameField.selectAll();

// Create the popup dialog box

final DialogBox dialogBox = new DialogBox();

dialogBox.setText("Remote Procedure Call");

dialogBox.setAnimationEnabled(true);

final Button closeButton = new Button("Close");

// We can set the id of a widget by accessing its Element

closeButton.getElement().setId("closeButton");

final Label textToServerLabel = new Label();

final HTML serverResponseLabel = new HTML();

VerticalPanel dialogVPanel = new VerticalPanel();

dialogVPanel.addStyleName("dialogVPanel");

dialogVPanel.add(new HTML("Sending name to the server:"));

dialogVPanel.add(textToServerLabel);

dialogVPanel.add(new HTML("
Server replies:"));

dialogVPanel.add(serverResponseLabel);

dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);

dialogVPanel.add(closeButton);

dialogBox.setWidget(dialogVPanel);

// Add a handler to close the DialogBox

closeButton.addClickHandler(new ClickHandler() {

public void onClick(ClickEvent event) {

dialogBox.hide();

sendButton.setEnabled(true);

sendButton.setFocus(true);

}

});

// Create a handler for the sendButton and nameField

class MyHandler implements ClickHandler, KeyUpHandler {

/**

* Fired when the user clicks on the sendButton.

*/

public void onClick(ClickEvent event) {

sendNameToServer();

}

/**

* Fired when the user types in the nameField.

*/

public void onKeyUp(KeyUpEvent event) {

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

sendNameToServer();

}

}

/**

* Send the name from the nameField to the server and wait for a response.

*/

private void sendNameToServer() {

// First, we validate the input.

errorLabel.setText("");

String textToServer = nameField.getText();

if (!FieldVerifier.isValidName(textToServer)) {

errorLabel.setText("Please enter at least four characters");

return;

}

// Then, we send the input to the server.

sendButton.setEnabled(false);

textToServerLabel.setText(textToServer);

serverResponseLabel.setText("");

greetingService.greetServer(textToServer,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

dialogBox

.setText("Remote Procedure Call - Failure");

serverResponseLabel

.addStyleName("serverResponseLabelError");

serverResponseLabel.setHTML(SERVER_ERROR);

dialogBox.center();

closeButton.setFocus(true);

}

public void onSuccess(String result) {

dialogBox.setText("Remote Procedure Call");

serverResponseLabel

.removeStyleName("serverResponseLabelError");

serverResponseLabel.setHTML(result);

dialogBox.center();

closeButton.setFocus(true);

}

});

}

}

// Add a handler to send the name to the server

MyHandler handler = new MyHandler();

sendButton.addClickHandler(handler);

nameField.addKeyUpHandler(handler);

}

}

GreetingService:

package ajaxGWTExample.client;

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

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

/**

* The client side stub for the RPC service.

*/

@RemoteServiceRelativePath("greet")

public interface GreetingService extends RemoteService {

String greetServer(String name) throws IllegalArgumentException;

}

GreetingServiceAsync:

package ajaxGWTExample.client;

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

/**

* The async counterpart of GreetingService.

*/

public interface GreetingServiceAsync {

void greetServer(String input, AsyncCallback callback)

throws IllegalArgumentException;

}

GreetingServiceImpl:

package ajaxGWTExample.server;

import ajaxGWTExample.client.GreetingService;

import ajaxGWTExample.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**

* The server side implementation of the RPC service.

*/

@SuppressWarnings("serial")

public class GreetingServiceImpl extends RemoteServiceServlet implements

GreetingService {

public String greetServer(String input) throws IllegalArgumentException {

// Verify that the input is valid.

if (!FieldVerifier.isValidName(input)) {

// If the input is not valid, throw an IllegalArgumentException back to

// the client.

throw new IllegalArgumentException(

"Name must be at least 4 characters long");

}

String serverInfo = getServletContext().getServerInfo();

String userAgent = getThreadLocalRequest().getHeader("User-Agent");

return "Hello, " + input + "!

I am running " + serverInfo

+ ".

It looks like you are using:
" + userAgent;

}

}



No comments: