GWT e mysql

18 respostas
J

Ola!
etou com um problema com a conexão ao mysql
quando tento executar a aplicaçao ele da esse erro


[ERROR] Line 14: No source code is available for type java.sql.Connection; did you forget to inherit a required module?
[ERROR] Line 17: No source code is available for type java.sql.DriverManager; did you forget to inherit a required module?
[ERROR] Line 18: No source code is available for type java.sql.SQLException; did you forget to inherit a required module?

alguem pode me ajudar??

obrigado :wink:

18 Respostas

A

ql ide vc usa… vc baixou o driver do banco q esta usando? criou a classe de conexao corretamente?

J

Eu estou usando o Netbeans 6.5.1
Sim baixei o conector j do mysql e coloquei ele no .lib do projeto
A classe de conexão esta correta é a mesma q eu utilizo para outras aplicações so q agora estou utilizando o GWT
e da esse erro.

A

Esses erros Connection- bom eh a conexão, criar um void main criar um obejto da conexao e testa os metodos conectar e desconectar

DriverManager- jah diver manager ve se vc add no lugar certo e se é o correto, baixe um novo qlqr coisa

SQLException- jah isso deve ser uma sql errada q vc ta passando…

A outra pergunta soh essa sql(nesse projeto q esta com pepino) naum funciona?

A

Uma coisa q naum tem nada a ver com sua duvida, mas to postando aki e ninguem responde, tem como me ajuda com?:

O q vc acha do java db?,

Depois de usar o javaDB naum precisa instalar mais nada se fosse uma aplicação desktop? ehj soh instalar a jvm e jah era?

J

Bom eu descobri qual q eh o problema

eh o seguinte o gwt possui dois lados o client e o server

a conexao q eu estou entanto fazer esta do lado client o q nao eh suportado pelo gwt

entao eu preciso executar ela no lado server e mandar os dados para o client utilizando um tal de RPC

alguem saberia me esplicar ou dar um exemplo de como eu faço isso

J

RESOLVIDO

bom eh o seguinte andei lendo alguns foruns e encontrei uma maneira de resolver isso.

para quem estiver com o mesmo problema ai vai o Link para o Tutorial q explica tudo certinho!

Obrigado :wink:

P

Exato, isso acontece pois o compilador do GWT conhece apenas a API do GWT para gerar Java Script. Qualquer coisa referente ao server-side, deve entrar no respectivo modulo via RPC = remote procedure call

B

Olá,

tem como passar o link novamente ? Não consegui acessar… Estou com o mesmo problema…

Desde já Obrigado,
Viva Java !

B

Não consigo acessar o site www.gwt.com.br

Tem outro link ? Você tem esse material para enviar ?

Preciso URGENTE…

Valeu,
Viva Java !

B

Aqui tem um tutorial de como fazer chamadas assíncronas em GWT. Entendeu isso, entendeu como usar o framework.

B

Bacana… Se eu enteder posso usar GWT com acesso a dados ? Acessar SQL ?

B

É claro que pode, do lado server você pode utilizar as APIs que quiser.

B

Você tem algum exemplo para mandar por email ?

J

Ola!
desculpe a demora para responder
como pedido vou postar um pequeno tutorial que esplica como fazer essa ligaçao server-side client-side

primeiro precisamos criar no pacote “CLIENTE” a interface GWTService.class

ai vai um exemplo do codigo fonte

//interface “GWTService.class”

package org.page.client;

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

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

//este eh o path do servlet q sera configurado
//mais tarde no arquivo web.xml
@RemoteServiceRelativePath(“GWTServiceImpl”)

public interface GWTService extends RemoteService{

public String getBoolean(boolean bo);

}

agora precisamos criar a outra interface “GWTServiceAsync”

ai vai o codigo fonte

//interface “GWTServiceAsync”

package org.page.client;

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

import com.google.gwt.user.client.rpc.RemoteService;
public interface GWTServiceAsync extends RemoteService{

public abstract void getBoolean(boolean bo, AsyncCallback callback);

}

agora vamos criar o servlet que ficara no pacote “SERVER” de nosso projeto

ai vai o codigo fonte

//-------------------------------------------------------------------------
package org.page.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.page.client.GWTService;

public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {

public String getBoolean(Boolean bo) {
         //aqui sera executada as funçoes do lado server
         //como acesso a arquivos, busca de dados em bd, etc
     return bo; // aki sera retornado o valor neste exemplo eh boolean mas pode ser qualquer um outro
}

}

feito isso devemos configurar o nosso servlet no arquivo web.xml com o path q esta configurado no arquivo GWTService.class

certo agora para chamar o metodo getBoolean colocamos isso no arquivo entryPoint

final GWTServiceAsync service = GWT.create(GWTService.class);

//chamada do metodo getBoolean enviando o valor boolean “true” para o servlet

service.getBoolean(true, new AsyncCallback (){

public void onFailure(Throwable caught) {

		//se ouver algum erro
                  RootPanel.get().add(new HTML(caught.toString());
}

public void onSuccess(boolean result) {

//se 	tudo der certo

RootPanel.get().add(new HTML(O valor retornado é + result);

}

});

é isso
esta meio complicado mas espero q consigam entender
qualquer duvida consultem a documentaçao do GWT
http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5

B

Não consegui fazer funcionar seu exemplo... Dá uma erro: Ja viu isso ?

com.google.gwt.user.client.rpc.StatusCodeException: 
HTTP Status 404 - /Portal/org.yournamehere.Main/GWTServiceImpl

--------------------------------------------------------------------------------

type Status report

message /Portal/org.yournamehere.Main/GWTServiceImpl

description The requested resource (/Portal/org.yournamehere.Main/GWTServiceImpl) is not available.


--------------------------------------------------------------------------------

Apache Tomcat/6.0.18
J

sim esse erro é porque o ele nao esta conseguindo encontrar o servlet para fazer a ligaçao

verifique o path do servlet se ele esta mesmo localizado em “/Portal/org.yournamehere.Main/GWTServiceImpl”

The requested resource (/Portal/org.yournamehere.Main/GWTServiceImpl) is not available. :wink:

vc pode mudar o path do servlet no arquivo GWTService.class

na linha:: “@RemoteServiceRelativePath(“GWTServiceImpl”)”

J
JDBC Connector

    * Add a JDBC connector jar to your Build Path
    * I put it here. My Projects are configured like: /opt/gwt-linux/mysql-connector-java-5.0.8-bin.jar
    * Check your Eclipse referenced libraries for jar
    * Example Eclipse Project Source code of Mysql Conn - http://gwt-examples.googlecode.com/svn/trunk/gwt-test-MySQLConn/src/com/tribling/gwt/test/mysqlconn/server/ 

    Links

    * JDBC Connector - http://www.mysql.com/products/connector/j/ - download MySQL Connector/J 5.1
    * Example MySQL Database, The King James Bible Download Bible Database Here (It comes as a MySQL Dump) 

Tomcat Setup

    When you use tomcat, the servlet container has to be given access outside of its container. More info here: gwtTomcat. 

    * Fix this problem: java.security.AccessControlException access denied (java.net.SocketPermission localhost resolve)
    * More information on this here: gwtTomcat 

    You will need to change Tomcat configuration.

    #for debian/ubuntu
    # I added to /etc/tomcat5.5/policy.d/04webapps.policy
    # Or make your own /etc/tomcat5.5/policy.d/myGWTPolicys.policy
    # you can also change file to: file:/apps/directory/yourGWTTomcatApps/- 
    grant codeBase "file:${catalina.home}/webapps/-" {
          permission java.net.SocketPermission "192.168.12.81:3306", "connect";
    };

Code Snippets

    MySQL Connection
    Connect to db. Don't forget to change the parameters.

    /**
     * db conn
     * 
     * Make sure you add a reference library (external jar in build path) JDBC Connector - 
     * You will see I put it in /opt/gwt-linux/mysql-connector-java-5.0.8-bin.jar
     * 
     * @return Connection
     */
    private Connection getConn() {

                Connection conn     = null;
                String url          = "jdbc:mysql://192.168.12.81:3306/";
                String db           = "hostdb";
                String driver       = "com.mysql.jdbc.Driver";
                String user         = "";
                String pass         = "";
                    
            try {
                    Class.forName(driver).newInstance();
            } catch (InstantiationException e) {
                    e.printStackTrace();
            } catch (IllegalAccessException e) {
                    e.printStackTrace();
            } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            }
            try {
                            
                            conn = DriverManager.getConnection(url+db, user, pass);
            } catch (SQLException e) {
                            System.err.println("Mysql Connection Error: ");
                    e.printStackTrace();
            }
                    return conn;
    }

    Get Row Count
    Use this to size an array for your values

    /*
     * get row count
     */
    protected static int getResultSetSize(ResultSet resultSet) {
        int size = -1;

        try {
            resultSet.last();
            size = resultSet.getRow();
            resultSet.beforeFirst();
        } catch(SQLException e) {
            return size;
        }

        return size;
    }

    Query
    Query statement, using connection, statement, resultset, and get record. Setup a connection first.

    String query = "SELECT * FROM table";
     
    try {
        Connection conn = this.getConn();
        Statement select = conn.createStatement();
        ResultSet result = select.executeQuery(query);
        while (result.next()) {
            String s = result.getString(1);
        }
        select.close();
        result.close();
        conn.close();
    } catch(SQLException e) {
            System.err.println("Mysql Statement Error: " + query);
            e.printStackTrace();
    }

    Update / Insert
    Update and Insert into database, MySql or MsSql or whatever database you have. Setup a connection first

    //save session data to table 
    String query = "INSERT INTO `session` (UserID, SessionID, LastAccessed, DateCreated) " +
                               "VALUES ('" + this.dbUserID + "', '" + this.SessionID + "' , UNIX_TIMESTAMP(), UNIX_TIMESTAMP());";

    try {
        Connection conn = this.getConn();
        Statement update = conn.createStatement();
        update.executeUpdate(query);
        
        //get last id 
        ResultSet result = update.getGeneratedKeys(); 
        if (result != null && result.next()) { 
            int rsId = result.getInt(1);  
        }

        result.close();
        update.close();
        conn.close();
    } catch(SQLException e) {
        System.err.println("Mysql Statement Error: " + query);
        e.printStackTrace();
    }

    Escape String For SQL
    Apache has some cool functions for escaping strings. This can only be run on server side, preparing the sql data for insert. You don't have to unescape b/c it comes out as is. It just allows you to save with "'" '"' in the string. 

    * Right Click Project > Build Path > Configure Build Path > Libraries > Add External Jar
    * Link to Apache jar documentation: Classes Documentation
    * Download Jar: Goto Download

      import org.apache.commons.lang.StringEscapeUtils;

      /**
       * escape string to db
       * @param s
       * @return
       */
      protected static String escapeForSql(String s) {

              String rtn = StringEscapeUtils.escapeSql(s);
              
              return rtn;
      }

    Improved Escape method for fixing data before its stuck into db

    /**
     * escape string to db
     * 
     * remove harmfull db content
     * remove harmfull tags
     *
     * @param s
     * @return
     */
    protected static String escapeForSql(String s) {
            
            //remove harmful HTML tags
            if (s != null) {
                    s = s.replaceAll("(?i)</?(HTML|SCRIPT|HEAD|CSS)\\b[^>]*>", ""); 
            }

            String rtn = StringEscapeUtils.escapeSql(s);
            
            //escape utils returns null if null
            if (rtn == null) {
                    rtn = "";
            }

            return rtn;
    }

Trasporting Data / Recordsets Around

    This is an example of how I transport data from server to client and back. This is my favorite way and by far the most efficient and easiest way to do it. 

    I use a class like this to store MySQL record set data into an object array. This makes it very easy to pass around data. Now if you use private methods and/or fields in the class that goes from server to client, you will have have to change Tomcat security. See more in gwtTomcat.

    /**
     * I use this class to store my mysql recordset in an object that is an array.
     * This will give an example of how I pass data from the server to client in an object, 
     * one of my favorites for its simplicity.
     * 
     * @author branflake2267
     *
     */
    public class BibleData implements IsSerializable {

            // fields to store data
            public String book;
            public int howManyChapters;
            public int howManyVerses;
            
            /**
             * constructor
             */
            public BibleData() {
                    // nothing to do when transporting
            }
            
    }

    This is an example of how I spool the data into the Object Array from MySQL.

    public BibleData[] getBibleInfo() {
            
            String query = "SELECT bid, en FROM book;";
            
            // prepare for rpc transport
            BibleData[] bibleData = null;
            
        try {
            Connection connection = getConn();
            Statement select = connection.createStatement();
            ResultSet result = select.executeQuery(query);
           
            // init object into the size we need, like a recordset
            int rsSize = getResultSetSize(result); //size the array
            bibleData = new BibleData[rsSize];
            
            int i = 0;
            while (result.next()) {
                    
                    // init each object in the array !!!!
                    bibleData[i] = new BibleData(); // <-THIS IS CRITICAL TO REMEMBER!!!! init each array with the object type (I forget to do this so often)
                    
                    int bid = result.getInt(1);
                    bibleData[i].book = result.getString(2);
                    bibleData[i].howManyChapters = getHowManyChapters(bid);
                    bibleData[i].howManyVerses = getHowManyVerses(bid);
                    
                i++;
            }
            
            // clean up
            result.close();
            connection.close();
            
        } catch(Exception e) {
            
            System.err.println("Mysql Statement Error: " + query);
            e.printStackTrace();
            
        }
            
        // return the array
        return bibleData;
    }

Feed Back Widget

The feedback widget in the repository gathers up the inputs and sends them to the server and inserts them into MySql.

    * Feedback widget Demo
    * SVN FeedBack Widget Project - Eclipse project for my Feedback widget 

    My Feedback Table

    CREATE TABLE `gv_feedback` (
      `ID` int(11) NOT NULL auto_increment,
      `UserID` int(11) default NULL,
      `FromEmail` varchar(150) default NULL,
      `FromName` varchar(150) default NULL,
      `Subject` varchar(250) default NULL,
      `Message` text,
      `Suggestion` tinyint(1) default '0',
      `Comment` tinyint(1) default '0',
      `Problem` tinyint(1) default '0',
      `Other` tinyint(1) default '0',
      `Post` tinyint(1) default NULL,
      `DateCreated` int(11) NOT NULL default '0',
      `LastUpdated` int(11) default NULL,
      PRIMARY KEY  (`ID`),
      KEY `UserID` (`UserID`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1

creditos:
http://code.google.com/p/gwt-examples/

L

Pessoal,

Vejo que vocês têm estrada no GWT. Então me permitam este pedido de ajuda.

Estou estudando o GWT com o eclipse há umas 2 semanas e de forma geral, estou entusiasmado com os resultados.

Mas ao tentar conectar com o banco de dados, lança o seguinte erro:

java.net.InetAddress is a restricted class. Please see the Google App Engine developer’s guide for more details.

Vocês já enfrentaram algo parecido? Há algum material que possam me indicar para superar esta questão?

Utilizo o Google Web Toolkit 2.0.4 e o Google App Engine.

Muito obrigado!

Criado 11 de julho de 2009
Ultima resposta 3 de set. de 2010
Respostas 18
Participantes 7