sábado, 21 de enero de 2012

Frameworks… Google Web Toolkit

Google Web Toolkit

Es un framework que permite crear aplicaciones web similares a aplicaciones de escritorio; posee componentes (controles) muy parecidos a los que tiene Java Swing:

1.       TextBox
2.       ListBox
3.        Image
4.       Tree
5.        Grid
6.       Window
7.        Etc. 

GWT compila el código Java y lo traduce a Javascript y HTML (algo parecido a lo que hace la librería dwr.jar).  


GWT y los IDEs
Creo la mejor forma de usar este framework es con  ayuda de un IDE como NetBeans  y/o Eclipse,  existen plugins para ambos y según yo no son difíciles de configurar.

¿Qué necesito para empezar con GWT?
1.       El SDK GWT
2.       El plugin (para NetBeans o Eclipse)
3.       Librerías gwtext, mejora muchos de los controles de gwt

Ejemplo 1. Un botón que activa una ventana “alert”.

package org.gwtprueba.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
/**
 * @author yo
 */
public class testGWTEntryPoint implements EntryPoint {
public void onModuleLoad() {
        Button btnActiva=new Button();
        btnActiva.setText("Activar mensaje");
        btnActiva.addListener(new ButtonListenerAdapter(){
        @Override
         public void onClick(Button btn, EventObject ev){
           Window.alert("Bienvenido usuario");
         }
        });
        RootPanel.get().add(btnActiva);
    }
}


Ejemplo 2. Crear un ejmeplo básico de GWT RPC









Automáticamente se generan  4 archivos java: GWTService.java, GWTServiceAsync.java, GWTServiceImpl.java y GWTServiceUsageExample.java (este es el archivo principal).
GWTService.java
package org.prueba.client;
import com.google.gwt.user.client.rpc.RemoteService;

public interface GWTService extends RemoteService{
    public String myMethod(String s,Integer e);
}

GWTServiceAsync.java
package org.prueba.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GWTServiceAsync {
    public void myMethod(String s,int e, AsyncCallback callback);
}

GWTServiceImpl.java
package org.prueba.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.redalyc.client.GWTService;

public class GWTServiceImpl extends RemoteServiceServlet implements
        GWTService {
   
    public String myMethod(String s,int e) {
        // Do something interesting with 's' here on the server.
        return "Hola: " + s+"   tienes  "+e+"   años";
    }
}
GWTServiceUsageExample.java
package org.prueba.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
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.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class GWTServiceUsageExample extends VerticalPanel {
    private Label lblServerReply = new Label();
    private TextBox txtNombre= new TextBox();
private TextBox  txtEdad = new TextBox();

    private Button btnSend = new Button("Enviar al servidor");
   
    public GWTServiceUsageExample() {
        add(new Label("Introduce tu nombre: "));
        add(txtNombre);
        add(new Label("Introduce tu edad: "));
        add(txtEdad);
        add(btnSend);
        add(lblServerReply);
       
        // Create an asynchronous callback to handle the result.
        final AsyncCallback callback = new AsyncCallback() {
            public void onSuccess(Object result) {
                lblServerReply.setText((String)result);
            }
           
            public void onFailure(Throwable caught) {
                lblServerReply.setText("Communicación fallida");
            }
        };
       
        // Listen for the button clicks
        btnSend.addClickListener(new ClickListener(){
            public void onClick(Widget w) {
                // Make remote call. Control flow will continue immediately and later
                // 'callback' will be invoked when the RPC completes.
                getService().myMethod(txtNombre.getText(),Integer.parseInt(txtEdad.getText()), callback);
            }
        });
    }
   
    public static GWTServiceAsync getService(){
        // Create the client proxy. Note that although you are creating the
        // service interface proper, you cast the result to the asynchronous
        // version of
        // the interface. The cast is always safe because the generated proxy
        // implements the asynchronous interface automatically.
        GWTServiceAsync service = (GWTServiceAsync) GWT.create(GWTService.class);
        // Specify the URL at which our service implementation is running.
        // Note that the target URL must reside on the same domain and port from
        // which the host page was served.
        //
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "gwtservice";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
}
Ahora falta crear la clase que lo muestre
package org.prueba.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
public class Prog01  implements EntryPoint {

    public void onModuleLoad() {
        RootPanel.get().add(new GWTServiceUsageExample());
    }

}


Página oficial, plugin para Eclipse

Plugin para NetBeans

Blog oficial GWT

SmartGWT

Demo GWT ext


Manual  GWT

Manual GWT ext

Libros

No hay comentarios:

Publicar un comentario

Vibe Coding (la programación vía IA): ¿el futuro de la programación?

Vibe Coding es un nuevo paradigma de programación, una nueva forma de crear código. Es un enfoque emergente en el desarrollo de sof...

Etiquetas

Archivo del blog