Mostrando entradas con la etiqueta gwt. Mostrar todas las entradas
Mostrando entradas con la etiqueta gwt. Mostrar todas las entradas

sábado, 17 de marzo de 2012

JSNI… JavaScript Native Interface (GWT)


JSNI es el mecanismo por el cual es posible invocar código javascript nativo (entre los comentarios /*-  -*/) desde código java.


Ejemplo  1. Ventana javascript dentro de código java (gwt).  
public static native void msg(String cad)/*-{
   $wnd.alert(‘Tu dices:  ’+cad);
}-*/;

Es necesario usar la palabra native y colocar las llaves dentro de comentarios para que el compilador java no lo considere un error.

//invoco el código javascript  dentro del código java
public void onModuleLoad(){
msg(“Es un buen día”);
}

Ejemplo 2. Manejar los mensajes tipo consola (firebug):
//defino los métodos  “logs”
public static native void info(Object obj)/*-{
   console.log(obj);
}-*/;

public static native void debug(Object obj)/*-{
   console.debug(obj);
}-*/;

public static native void warning(Object obj)/*-{
   console.warn(obj);
}-*/;

public static native void error(Object obj)/*-{
   console.error(obj);
}-*/;
Ahora invocarlos en código java
public void onModuleLoad(){
info(“iniciando aplicación web…”);
try{
debug(“se ha creado el objeto satisfactoriamente”);
warning(“esperando un error”);
}catch(Exception ex){
error(“error encontrado:  ”+ex+” causa: ”+ex.getCause());
}
}

Para poder ver los mensajes es necesario activar firebug dentro de firefox o chrome. Esto puede ser una buena práctica de testing.


Ejemplo 3. Contenido html

public static native void contenido()/*-{
document.write(“<h1>GWT ejemplos</h1>”);
}-*/;
//invocar el método
public void onModuleLoad(){
       contenido();
      RootPanel.get().add(new  Acceso.getVista());
}

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

Jai un lenguaje de programación inspirado en C++

Hoy hablaremos de un nuevo lenguaje de programación llamado Jai . Se trata de un lenguaje de programación que está desarrolland...

Etiquetas

Archivo del blog