GWT + Hibernate!

3 respostas
juniorsatanas

Pessoal, estou estudando GWT, ta feio 2 x 0 para ele !

Alguém sabe onde encontro um exemplo que tenha:

1 - conecta no banco mysql
2 - cadastra um usuario
3- loga o usuario
4- cadastra/pesquisa/deleta/adiciona/ produto

báico…

abraço valeu !

3 Respostas

eltonphysics

junior, para criar esse CRUD vc deve realizar chamada procedimento remoto primeiramente.

1.: deve-se criar 2 interfaces -> sincrona e assincrona
2.: 1 servlet que conterá conteudo de seus metodos e que implementa a interface sincrona
3.: apos isso, coloca no lado cliente(na parte de sua aplicação) essa declaração->

public static GWTServiceAsync getService() {

return GWT.create(GWTService.class);//lado sincrono. Tem como retorno o lado assincrono

}

4.: Por fim. vc acessa  : getService.Cadastra(objeto), como por exemplo, suas interfaces deverao estar assim:
@RemoteServiceRelativePath(gwtservice)//serve para declaração XML

public interface GWTService extends RemoteService {

public void Cadastra( Object objeto);

}
public interface GWTServiceAsync {

public void Cadastra(Object object, AsyncCallback asyncCallback);

}

Nao esqueça do XML deve estar com o trecho.:

GWTService org.yournamehere.server.br.com.GWTServiceImpl GWTService /org.yournamehere.Main/gwtservice
juniorsatanas

eltonphysics Bom dia e Obrigado !

estou fazendo asssim :

Configuração do NetBeans:

1- Instale o plugin gwt4nb (GWT) no NetBeans;

2- Inicie ou importe um novo projeto e configure a memória virtual seguindo o seguinte passo:

Dentro da pasta do projeto, procure o arquivo build-gwt.xml, que está na pasta nbproject.

Verá um código como esse:

<java classpath=?${javac.classpath}:${src.dir}? failonerror=?true?

classname=?com.google.gwt.dev.GWTCompiler? fork=?true?>

<arg value=?-out?/>

<arg path=?${build.web.dir}/?/>

<arg value=?-style?/>

<arg value=?${gwt.compiler.output.style}?/>

<arg value=?-logLevel?/>

<arg value=?${gwt.compiler.logLevel}?/>

<arg value=?${gwt.module}?/>

</java>

Insira essa tag abaixo como no local em negrito no código:

<jvmarg value=?-Xmx512m? />

<java classpath=?${javac.classpath}:${src.dir}? failonerror=?true?

classname=?com.google.gwt.dev.GWTCompiler? fork=?true?>

<arg value=?-out?/>

<arg path=?${build.web.dir}/?/>

<arg value=?-style?/>

<arg value=?${gwt.compiler.output.style}?/>

<arg value=?-logLevel?/>

<arg value=?${gwt.compiler.logLevel}?/>

<arg value=?${gwt.module}?/>

<jvmarg value=?-X m x 5 1 2 m? />

</java>

3- Para a conexão com o banco de dados configure o hibernate-config de acordo com as

entidades contidas no modelo de negócio do projeto;

4-Páginas da web, javascripts e css devem ficar no pacote ?Paginas da Web? :
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

    &lt;head&gt;

      &lt;meta   http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;

		&lt;style type="text/css"&gt;

	        #loading {

	            position: absolute;

	            left: 45%;

	            top: 40%;

	            padding: 2px;

	            z-index: 20001;

	            height: auto;

	            border: 1px solid #ccc;

	        }

	        #loading a {

	            color: #225588;

	        }



	        #loading .loading-indicator {

	            background: white;

	            color: #444;

	            font: bold 13px tahoma, arial, helvetica;

	            padding: 10px;

	            margin: 0;

	            height: auto;

	        }



	        #loading-msg {

	            font: normal 10px arial, tahoma, sans-serif;

	        }

    	&lt;/style&gt;





		&lt;title&gt;TesteGWT&lt;/title&gt;



		&lt;!--                                           --&gt;

		&lt;!-- Use normal html, such as style            --&gt;

		&lt;!--                                           --&gt;

		&lt;style&gt;

			body,td,a,div,.p{font-family:arial,sans-serif}

			div,td{color:#000000}

			a:link,.w,.w a:link{color:#0000cc}

			a:visited{color:#551a8b}

			a:active{color:#ff0000}

		&lt;/style&gt;

    &lt;/head&gt;

    &lt;body&gt;

        		&lt;!--add loading indicator while the app is being loaded--&gt;

		&lt;div id="loading"&gt;

		    &lt;div class="loading-indicator"&gt;

		        <img   

		             />TesteGWT-Ext<br/>

		        &lt;span id="loading-msg"&gt;Carregando estilos e imagens...&lt;/span&gt;&lt;/div&gt;

		&lt;/div&gt;



		&lt;!--include the Ext CSS, and use the gray theme--&gt;

		&lt;link rel="stylesheet" type="text/css" href="js/ext/resources/css/ext-all.css"/&gt;





		&lt;script type="text/javascript"&gt;document.getElementById('loading-msg').innerHTML = 'Carregando fontes...';&lt;/script&gt;

		&lt;!--include the Ext Core API--&gt;

		&lt;script type="text/javascript" src="js/ext/adapter/ext/ext-base.js"&gt;&lt;/script&gt;



		&lt;!--include Ext --&gt;

		&lt;script type="text/javascript"&gt;document.getElementById('loading-msg').innerHTML = 'Carregando Componentes...';&lt;/script&gt;

		&lt;script type="text/javascript" src="js/ext/ext-all.js"&gt;&lt;/script&gt;

		&lt;script type="text/javascript" src="js/ext/source/locale/ext-lang-pt_BR.js"&gt;&lt;/script&gt;



		&lt;!--include the application JS--&gt;

		&lt;script type="text/javascript"&gt;document.getElementById('loading-msg').innerHTML = 'Inicializando...';&lt;/script&gt;

		&lt;script language="javascript" src="org.yournamehere.Main/org.yournamehere.Main.nocache.js"&gt;&lt;/script&gt;

		&lt;!--hide loading message--&gt;



		&lt;script type="text/javascript"&gt;Ext.get('loading').fadeOut({remove: true, duration:.25});&lt;/script&gt;

        

    &lt;/body&gt;

&lt;/html&gt;
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
&lt;hibernate-configuration&gt;
  &lt;session-factory&gt;
    &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.DerbyDialect&lt;/property&gt;
    &lt;property name="hibernate.connection.driver_class"&gt;org.apache.derby.jdbc.ClientDriver&lt;/property&gt;
    &lt;property name="hibernate.connection.url"&gt;jdbc:derby://localhost:1527/travel&lt;/property&gt;
    &lt;property name="hibernate.connection.username"&gt;travel&lt;/property&gt;
    &lt;property name="hibernate.connection.password"&gt;travel&lt;/property&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
/*
 * MainEntryPoint.java
 *
 * Created on 6 de Janeiro de 2010, 15:55
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.yournamehere.client;

import com.google.gwt.core.client.EntryPoint;




public class MainEntryPoint implements EntryPoint {
    
    /** Creates a new instance of MainEntryPoint */
    public MainEntryPoint() {
    }
    
    /**
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    public void onModuleLoad() {
        GWTServiceTesteUsageExample janela = new GWTServiceTesteUsageExample();
		janela.show();
    }
    
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.yournamehere.client;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.MessageBoxConfig;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.WaitConfig;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Label;

public class JanelaApresenta extends Window{
    
    private Panel painel;
    private Label label;
    private Button botao;

    public JanelaApresenta(){

        painel = new Panel();
        painel.setTitle("TesteGWT-Ext");
        painel.setSize(800, 600);
        

        label = new Label();
        label.setWidth(300);

        botao = new Button("Clicar", new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e) {
                label.setText("Olá");
                AsyncCallback&lt;?&gt; call = new AsyncCallback() {
						public void onFailure(Throwable caught) {
							MessageBox.hide();
							MessageBox.alert("erro");
						}

						public void onSuccess() {
							MessageBox.hide();

							// Fecha essa janela com uma mensagem de confirmação
							
							MessageBox.alert("Comissao Salva com Sucesso!");

						}

                    public void onSuccess(Object result) {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }
					};

					/**
					 * Chamada ao processo assíncrono para salvar a comissão no
					 * banco de dados
					 */
					GWTServiceTesteAsync service = GWTServiceTeste.Util.getInstance();
					service.myMethod(id, call);

					MessageBox.show(new MessageBoxConfig() {
						{
							setMsg("Criando Conexão");
							setProgressText("Processando...");
							setWidth(300);
							setWait(true);
							setWaitConfig(new WaitConfig() {
								{
									setInterval(200);
								}
							});
						}
					});

			}
	});



        painel.add(label);
        painel.add(botao);

        this.add(painel);

    }

}
/*
 * GWTServiceTesteUsageExample.java
 *
 * Created on 6 de Janeiro de 2010, 17:31
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.yournamehere.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.TextBox;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Label;



public class GWTServiceTesteUsageExample extends Window {
    private Label lblServerReply = new Label();
    private TextBox txtUserInput = new TextBox();
    private Button btnSend = new Button("Enviar ao servidor");
    
    public GWTServiceTesteUsageExample() {
        setSize(800, 600);
        setTitle("GWT-Ext Teste");
        add(new Label("Escreva um texto aqui: "));
        add(txtUserInput);
        add(btnSend);
        add(lblServerReply);
        
        /* Cria um asynchronous callback para trazer o resultado do servidor.
         * Esse método chama as interfaces service e service assíncrona visando
         * a conexão com o servlet. */
        final AsyncCallback callback = new AsyncCallback() {
            public void onSuccess(Object result) {
                lblServerReply.setText((String)result);
            }
            
            public void onFailure(Throwable caught) {
                lblServerReply.setText("Falha na comunicação");
            }
        };
        
        // Listen for the button clicks
        btnSend.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e) {
                // Make remote call. Control flow will continue immediately and later
                // 'callback' will be invoked when the RPC completes.
                getService().myMethod(txtUserInput.getText(), callback);
            }
        });
    }
    
    public static GWTServiceTesteAsync 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.
        GWTServiceTesteAsync service = (GWTServiceTesteAsync) GWT.create(GWTServiceTeste.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() + "gwtserviceteste";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
}
/*
 * GWTServiceTesteAsync.java
 *
 * Created on 6 de Janeiro de 2010, 17:31
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.yournamehere.client;
import com.google.gwt.user.client.rpc.AsyncCallback;




public interface GWTServiceTesteAsync {
    public void myMethod(String s, AsyncCallback callback);
}
/*
 * GWTServiceTeste.java
 *
 * Created on 6 de Janeiro de 2010, 17:31
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.yournamehere.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.ServiceDefTarget;


public interface GWTServiceTeste extends RemoteService{

    public static final String SERVICE_URI = "/org.yournamehere.Main/gwtserviceteste";
    public String myMethod(String s);

    	public static class Util {

		public static GWTServiceTesteAsync getInstance() {

			GWTServiceTesteAsync instance = (GWTServiceTesteAsync) GWT.create(GWTServiceTeste.class);
			ServiceDefTarget target = (ServiceDefTarget) instance;
			target.setServiceEntryPoint(GWT.getModuleBaseURL() + SERVICE_URI);
			return instance;

		}
	}

}
eltonphysics

4-Páginas da web, javascripts e css devem ficar no pacote ?Paginas da Web? :
R= em paginas da web, desculpe a demora, nao chegou o email avisando sobre a duvida

Criado 25 de dezembro de 2009
Ultima resposta 18 de mar. de 2010
Respostas 3
Participantes 2