Tuesday, July 7, 2009

Integrate GWT into Struts 2 Application

Source of this tutorial: http://cwiki.apache.org/WW/struts-2-gwt.html

These tutorial will demonstrate how to call an Struts 2 action, using GWT to submit a form and use the returned data.

Write your action.

Example action:

"Hello.java"
package example;

import com.opensymphony.xwork2.Action;

public class Hello {
private String firstName;
private String lastName;

public String execute() {
return Action.SUCCESS;
}

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

Write the mapping for your action.

In this example the mapping is in struts.xml:

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="example" extends="struts-default">
<action name="Hello" class="example.Hello">
<result type="json" />
</action>

<action name="Main" class="com.opensymphony.xwork2.ActionSupport">
<result>org.apache.struts.gwt.Main/Main.jsp</result>
</action>
</package>

</struts>




The "Hello" action has a result of type "json", which will serialize the action object into a JSON

string. If "firstName" is set to "John" and "lastName" is set to "Galt", the output of the "Hello" action will be:

{
"firstName" : "John",
"lastName" : "Galt"
}

The "Main" action points to the "Main.jsp" page which is the page that uses GWT. The path of the result is "org.apache.struts.gwt.Main/Main.jsp". That means that the files generated by GWT must go under a folder named "org.apache.struts.gwt.Main" under the root of your application. See "Deployment structure" for more details.

Write "Main.jsp" page.

This is the page that is generated by GWT's "applicationCreator". It has been renamed to .jsp because we have modified it to be a jsp page, instead of a plain html page.

Main.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head theme="ajax" debug="true"/>
<meta name='gwt:module' content='org.apache.struts.gwt.Main/org.apache.struts.gwt.Main'>
</head>

<body>
<script language="javascript" src="${pageContext.request.contextPath}/org.apache.struts.gwt.Main/gwt.js"/>

<form id="form1">
<input type="text" name="firstName">
<br/>
<input type="text" name="lastName">
<span id="slot1"></span>
</form>

<br/>
<span id="slot2"></span>
</body>
</html>

We set head's tag attribute "theme" to ajax to use Dojo, don't panic, you won't have to use it directly. Note that we have changed a few things from the original html page generated by GWT, we set "content" to "org.apache.struts.gwt.Main/org.apache.struts.gwt.Main" because the GWT generated files will be under "AppRoot/org.apache.struts.gwt.Main" instead of beneath root, and we set "src" to "${pageContext.request.contextPath}/org.apache.struts.gwt.Main/gwt.js" for the same reason. Without these two changes the GWT files wouldn't be loaded.
Struts2GWTHelper

This class will take care of making the request. Why? Why do I need this class? Couple of reasons, first, there is a bug on bug on HTTPRequest.asyncPost which doesn't encode the payload properly, second, if you want to submit a form, you have to encode it yourself, and this class will help you do that. Optionally you can download a jar containing this class (with more methods) from here, add this to your GWT application file (i.e Main.gwt.xml):

<inherits name='struts2gwt.Struts2GWT'/>

and add the jar to the classpath in your compile script (i.e Main-compile.cmd) and the compile script (i.e Main-shell.cmd).
Struts2GWTHelper .java

package org.apache.struts.gwt.client;

import com.google.gwt.user.client.ResponseTextHandler;

public class Struts2GWTHelper {

/**
* Make asynchronous post
* @param url Action url
* @param formId id of form that will be posted
* @param handler callback function
*/
public static native void asyncPost(String url, String formId, ResponseTextHandler handler) /*-{
dojo = $wnd.dojo;
//don't use the dojo.io.bind({...}) shortcut, it doesn't work here
var request = new dojo.io.Request(url);
request.load = function(type, data, request) {
handler.@com.google.gwt.user.client.ResponseTextHandler::onCompletion(Ljava/lang/String;)(data);
};
request.formNode = dojo.byId(formId);
request.method = "POST";
$wnd.dojo.io.bind(request);
}-*/;

/**
* Make asynchronous post
* @param url Action url
* @param handler callback function
*/
public static void asyncPost(String url, ResponseTextHandler handler) {
Struts2GWTHelper.asyncPost(url, handler);
}
}

See? It wasn't that bad.
Write your GWT entry point
Main.java

package org.apache.struts.gwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ResponseTextHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Main implements EntryPoint {
final Label label = new Label();

/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button button = new Button("Click me");

button.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
makeRequest();
}
});

RootPanel.get("slot1").add(button);
RootPanel.get("slot2").add(label);
}

private void makeRequest() {
Struts2GWTHelper.asyncPost("Hello.action", "form1", new ResponseTextHandler() {
public void onCompletion(String responseText) {
JSONObject obj = (JSONObject)JSONParser.parse(responseText);
JSONString firstName = (JSONString)obj.get("firstName");
JSONString lastName = (JSONString)obj.get("lastName");
label.setText("Welcome " + firstName.stringValue() + " " + lastName.stringValue());
}
});
}
}

The makeRequest() method will make a request to the "Hello" action that we created before, and will pass the fields of the form "form1" as parameters. Which will be populated on the action, and serialized back as JSON. Using JSONParser the JSON string is parsed into a JSON object. It is definitely not type safe as GWT Remoting, but it works.
Create Main.gwt.xml

Nothing new on this file, just as reference:
Main.gwt.xml

<module>

<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.google.gwt.json.JSON'/>

<!-- Specify the app entry point class. -->
<entry-point class='org.apache.struts.gwt.client.Main'/>

</module>

Deployment structure
Folder Notes
AppRoot The application deployment folder
AppRoot/index.html Welcome Page
AppRoot/org.apache.struts.gwt.Main Content generated by GWT (usually it gets generated into a folder named 'www')
AppRoot/WEB-INF Regular webapp files and classes


A GWT app: HouseOnMaps.com

Here got a web site 100% developed in GWT. It's House On Maps Dot Com @ www.houseonmaps.com

I think the Google map is loaded a bit slow. Perhaps there should be a trick to make it faster.

GWT-Ext


Source: http://gwt-ext.com/ (official site of GWT-Ext)
GWT-Ext is a powerful widget library that provides rich widgets like Grid with sort, paging and filtering, Tree’s with Drag & Drop support, highly customizable ComboBoxes, Tab Panels, Menus & Toolbars, Dialogs, Forms and a lot more right out of the box with a powerful and easy to use API. It uses GWT and Ext.

GWT-Ext 2.0.5 has been released. Grab the distribution from the Downloads area. GWT-Ext 2.0.5 supports GWT 1.5 final (1.5.2), Firefox3 and Chrome.

Note that GWT-Ext only supports Ext 2.0.2 that has a LGPL license option.

The download link for current latest version of GWT-Ext (GWT-Ext 2.0): http://gwt-ext.com/demo

Tuesday, January 15, 2008

gwt window manager

Just now, I found that other people have done the same thing as mine, even better than the one I did. They really have done a great job.. that they put a lot of animations, transparent backgrounds, sophisticated window buttons (e.g: vista & iMac themes), etc.
They called it GWT Window Manager. You can find out more from this link:

http://www.gwtwindowmanager.org/

gwt window demo

I have made the demo of gwt window (as shown in the figure below):












You can go to the link below to view the demo:

http://www.euzertech.com/gwt/gwtwindow.html


The source files of this demo project can be downloaded from this link:

http://www.euzertech.com/gwt/gwtwindow.zip

Please note that the background and border color of the window dialogbox generated by my Window class is transparent. So, you can use external CSS to color the window. In this demo, the source code of my CSS is as below:

.gwt-Window {
background-color: #0055ff;
border-color: #0000ff;
border-style: solid;
border-width: 2px;
}

.gwt-Window .HeadPanel {
background-color: #00eeff;
}

.gwt-Window .HeadPanel .Caption {
font-weight: bold;
}


Please note that in order to use the "Window.java", 6 images files (close.png, close_white.png, minimize.png, minimize_white.png, maximize.png, maximize_white.png) must be included in the same folder. You can see the files structure of the demo from the figure below:

Monday, January 14, 2008

gwt window dialogbox widget with minimize and close buttons

I wanted to make a draggable window dialog box with minimize and close buttons on the caption panel, but i couldn't find this kind of gwt widget API from the web. So, i have decided to build my own one by modifying the source code from a gwt library file called "DialogBox.java". Below is the source code of my "Window.java":

/*
* Copyright 2007 Google Inc.
*
* Modified from DialogBox.java of GWT 1.4.61
* by Wong Thai Min at 14th January 2008.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.thaimin.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.MouseListener;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ImageBundle;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
* A form of popup window that has a caption area at the top and can be dragged by the
* user. Minimize, maximize and close window buttons are on the caption area.
*
* CSS Style Rules
*
* .gwt-Window { the outside of the window }
* .gwt-Window .HeadPanel { the header panell of the window }
* .gwt-Window .HeadPanel .Caption { the caption }
*
*/
public class Window extends PopupPanel implements MouseListener {

public interface WindowImages extends ImageBundle {

AbstractImagePrototype maximize();

AbstractImagePrototype maximize_white();

AbstractImagePrototype minimize();

AbstractImagePrototype minimize_white();

AbstractImagePrototype close();

AbstractImagePrototype close_white();
}
public static final WindowImages images = (WindowImages) GWT.create(WindowImages.class);
private Image minmax = images.minimize().createImage();
private Image close = images.close().createImage();
private HorizontalPanel icons = new HorizontalPanel();
private HorizontalPanel headhor = new HorizontalPanel();
private VerticalPanel headver = new VerticalPanel();
private FlexTable content = new FlexTable();
private Label caption = new Label();
private Widget child;
private boolean dragging;
private int dragStartX, dragStartY;
private FlexTable panel = new FlexTable();

/**
* Creates an empty dialog box. It should not be shown until its child widget
* has been added using {@link #add(Widget)}.
*/
public Window() {
this(false);
}

/**
* Creates an empty dialog box specifying its "auto-hide" property. It should
* not be shown until its child widget has been added using
* {@link #add(Widget)}.
*
* @param autoHide true if the dialog should be automatically
* hidden when the user clicks outside of it
*/
public Window(boolean autoHide) {
this(autoHide, true);
}

/**
* Creates an empty dialog box specifying its "auto-hide" property. It should
* not be shown until its child widget has been added using
* {@link #add(Widget)}.
*
* @param autoHide true if the dialog should be automatically
* hidden when the user clicks outside of it
* @param modal true if keyboard and mouse events for widgets
* not contained by the dialog should be ignored
*/
public Window(boolean autoHide, boolean modal) {
super(autoHide, modal);

// minimize & close buttons for DialogBox
minmax.setTitle("minimize");
close.setTitle("close");

// panel:headver:headhor:icons HorizontalPanel ==> display minmax & close images
icons.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
icons.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
icons.setHeight("100%");
icons.setSpacing(2);
icons.add(minmax);
icons.add(close);

// panel:headver:headhor HorizontalPanel
headhor.setWidth("100%");
headhor.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
headhor.add(caption);
headhor.setCellWidth(caption, "100%");
headhor.setCellHorizontalAlignment(caption, HorizontalPanel.ALIGN_LEFT);
headhor.add(icons);
headhor.setCellHorizontalAlignment(icons, HorizontalPanel.ALIGN_RIGHT);

// panel:headver:content VerticalPanel

// panel:headver VerticalPanel
headver.setWidth("100%");
headver.add(headhor);
headver.add(content);

// panel Flextable
panel.setWidget(0, 0, headver);
panel.setHeight("100%");
panel.setBorderWidth(0);
panel.setCellPadding(0);
panel.setCellSpacing(0);
panel.getCellFormatter().setHeight(1, 0, "100%");
panel.getCellFormatter().setWidth(1, 0, "100%");
panel.getCellFormatter().setAlignment(1, 0,
HasHorizontalAlignment.ALIGN_CENTER,
HasVerticalAlignment.ALIGN_MIDDLE);

// Display the layout of the window
super.setWidget(panel);

setStyleName("gwt-Window");
headhor.setStyleName("HeadPanel");
caption.setStyleName("Caption");
caption.addMouseListener(this);

//---------------------- Mouse Listener for window buttons -----------------
minmax.addMouseListener(new MouseListener() {

public void onMouseDown(Widget sender, int x, int y) {
}

// Minimize(grey) icon become white color
public void onMouseEnter(Widget sender) {
if (isMinimize()) {
images.maximize_white().applyTo(minmax);
} else {
images.minimize_white().applyTo(minmax);
}
}

public void onMouseLeave(Widget sender) {
if (isMinimize()) {
images.maximize().applyTo(minmax);
} else {
images.minimize().applyTo(minmax);
}
}

public void onMouseMove(Widget sender, int x, int y) {
}

public void onMouseUp(Widget sender, int x, int y) {
if (isMinimize()) {
setMinimize(false);
} else {
setMinimize(true);
}
}
});

close.addMouseListener(new MouseListener() {

public void onMouseDown(Widget sender, int x, int y) {
}
// Close(grey) icon become white color
public void onMouseEnter(Widget sender) {
images.close_white().applyTo(close);
}

public void onMouseLeave(Widget sender) {
images.close().applyTo(close);
}

public void onMouseMove(Widget sender, int x, int y) {
}

public void onMouseUp(Widget sender, int x, int y) {
}
});

// Close the window
close.addClickListener(new ClickListener() {

public void onClick(Widget sender) {
hide();
}
});
//------------------ End of Mouse Listener for window buttons ------------------
}

public String getText() {
return caption.getText();
}

public boolean onEventPreview(Event event) {
// We need to preventDefault() on mouseDown events (outside of the
// DialogBox content) to keep text from being selected when it
// is dragged.
if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
if (DOM.isOrHasChild(caption.getElement(), DOM.eventGetTarget(event))) {
DOM.eventPreventDefault(event);
}
}

return super.onEventPreview(event);
}

public void onMouseDown(Widget sender, int x, int y) {
dragging = true;
DOM.setCapture(caption.getElement());
dragStartX = x;
dragStartY = y;
}

public void onMouseEnter(Widget sender) {
}

public void onMouseLeave(Widget sender) {
}

public void onMouseMove(Widget sender, int x, int y) {
if (dragging) {
int absX = x + getAbsoluteLeft();
int absY = y + getAbsoluteTop();
setPopupPosition(absX - dragStartX, absY - dragStartY);
}
}

public void onMouseUp(Widget sender, int x, int y) {
dragging = false;
DOM.releaseCapture(caption.getElement());
}

public boolean remove(Widget w) {
if (child != w) {
return false;
}

panel.remove(w);
return true;
}

/**
* Set the caption of the window.
*
* @param text
*/
public void setText(String text) {
caption.setText(text);
}

/**
* Insert a content widget into the window. If there is any widget in the
* content area of the window, it will be removed and replaced by
* w.
*
* @param w The content widget to be inserted to the Window.
*/
public void setWidget(Widget w) {
// If there is already a widget, remove it.
if (child != null) {
content.remove(child);
}

// Add the widget to the center of the cell.
if (w != null) {
content.setWidget(1, 0, w);
}

child = w;
}

/**
* Override, so that interior panel reflows to match parent's new width.
*
* @Override
*/
public void setWidth(String width) {
super.setWidth(width);

// note that you CANNOT call panel.setWidth("100%") until parent's width
// has been explicitly set, b/c until then parent's width is unconstrained
// and setting panel's width to 100% will flow parent to 100% of browser
// (i.e. can't do this in constructor)
panel.setWidth("100%");
}

/**
* Determines whether the window state is currently minimized or restored.
*/
public boolean isMinimize() {
return !content.isVisible();
}

/**
* Set the window state whether to be minimized or restored.
*
* @param state true to minimize the window.
*/
public void setMinimize(boolean b) {
content.setVisible(!b);
if (b = true) {
images.maximize().applyTo(minmax);
} else {
images.minimize().applyTo(minmax);
}
}
}