Vai precisar destas bibliotecas:
Banco:
CREATE TABLE produtos
(
id serial NOT NULL,
nome character varying(50),
preco double precision,
marca character varying(50),
id_categoria integer,
CONSTRAINT ijdpk PRIMARY KEY (id)
)
WITH (OIDS=FALSE);
ALTER TABLE produtos OWNER TO postgres;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app id="WebApp_ID">
<display-name>gwtext</display-name>
<context-param>
<description>Define o tipo de servidor do GWT</description>
<param-name>GWT_MODE</param-name>
<param-value>WEB_MODE</param-value>
</context-param>
<servlet>
<servlet-name>GwtExtService</servlet-name>
<servlet-class>
exemplo.teste.server.GwtExtServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GwtExtService</servlet-name>
<url-pattern>/servico</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>gwtext.html</welcome-file>
</welcome-file-list>
</web-app>
caminho:
WebContent/WEB-INF/classes
conexaoteste.xml
<dados>
<conexao>
<host>localhost</host>
<sgbd>postgresql</sgbd>
<database>postgres</database>
<user>postgres</user>
<password>postgres</password>
</conexao>
</dados>
BEANS
CarregarDadosBean.java
package exemplo.teste.beans;
import com.google.gwt.user.client.rpc.IsSerializable;
public class CarregarDadosBean implements IsSerializable{
private Integer id;
private String nome;
private Double preco;
private String marca;
private Integer id_categoria;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Double getPreco() {
return preco;
}
public void setPreco(Double preco) {
this.preco = preco;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public Integer getId_categoria() {
return id_categoria;
}
public void setId_categoria(Integer id_categoria) {
this.id_categoria = id_categoria;
}
}
CLIENT
Constantes.java
package exemplo.teste.client;
public class Constantes {
// Modo do servidor GWT
public static String GWT_MODE = "GWT_MODE";
public static String HOSTED_MODE = "HOSTED_MODE";
public static String WEB_MODE = "WEB_MODE";
}
gwtext.java
package exemplo.teste.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Timer;
public class gwtext implements EntryPoint {
public void onModuleLoad() {
final JanelaTeste janelaTeste = new JanelaTeste();
Timer t = new Timer(){
@Override
public void run() {
janelaTeste.show();
}
};
t.schedule(1000);
}
}
GwtExtService.java
package exemplo.teste.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 GwtExtService extends RemoteService {
public static final String SERVICE_URI = "/servico";
public abstract String[][] carregarDados() throws Exception;
public static class Util {
public static GwtExtServiceAsync getInstance() {
GwtExtServiceAsync instance = (GwtExtServiceAsync) GWT
.create(GwtExtService.class);
ServiceDefTarget target = (ServiceDefTarget) instance;
target.setServiceEntryPoint(GWT.getModuleBaseURL() + SERVICE_URI);
return instance;
}
}
}
GwtExtServiceAsync.java
package exemplo.teste.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GwtExtServiceAsync {
public abstract void carregarDados(AsyncCallback callback);
}
JanelaTeste.java
package exemplo.teste.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.FieldSet;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtextux.client.data.PagingMemoryProxy;
import com.gwtextux.client.widgets.grid.plugins.GridSearchPlugin;
public class JanelaTeste extends Window{
private Panel painel;
private Label label;
private Button botao, button;
private static Object[][] dado = new Object[0][0];
private FieldSet fieldSet, fieldDecor;
private GridPanel grid;
private JanelaTestes janelaTestes;
private String url = "http://www.gwt-ext.com/demo/";
public JanelaTeste() {
AsyncCallback<Object> callback = new AsyncCallback<Object>(){
public void onFailure(Throwable caught) {
MessageBox.alert("Não foi possível carregar os dados!");
}
public void onSuccess(Object result) {
dado = (Object[][]) result;
JanelaTeste.this.setSize(800, 600);
JanelaTeste.this.setTitle("GWT-Ext");
painel = new Panel();
painel.setSize(785, 585);
fieldSet = new FieldSet();
fieldSet.setAutoHeight(false);
fieldSet.setAutoWidth(false);
fieldSet.setSize(782, 530);
fieldDecor = new FieldSet();
fieldDecor.setAutoHeight(false);
fieldDecor.setAutoWidth(false);
fieldDecor.setSize(782, 30);
label = new Label();
label.setSize(200, 30);
botao = new Button("Clique", new ButtonListenerAdapter(){
public void onClick(Button button, EventObject e){
label.setText("Ola!!! Esse e o GWT-Ext");
}
});
button = new Button("Dados", new ButtonListenerAdapter(){
public void onClick(Button button, EventObject e){
abrirHtml(url);
}
});
fieldDecor.add(label);
getGridPanel();
fieldSet.add(grid);
fieldSet.setButtonAlign(Position.CENTER);
fieldSet.addButton(botao);
fieldSet.addButton(button);
painel.add(fieldDecor);
painel.add(fieldSet);
JanelaTeste.this.add(painel);
}
};
GwtExtServiceAsync service = GwtExtService.Util.getInstance();
service.carregarDados(callback);
}
public GridPanel getGridPanel(){
grid = new GridPanel();
ColumnConfig[] columns = new ColumnConfig[]{
new ColumnConfig("Id", "id",50, true, null,"id"),
new ColumnConfig("Nome", "nome", 300, true, null, "nome"),
new ColumnConfig("Preco", "preco", 50, true, null, "preco"),
new ColumnConfig("Marca", "marca", 200, true, null, "marca"),
new ColumnConfig("Categoria", "id_categoria", 80, true, null, "id_categoria")
};
RecordDef recordDef = new RecordDef(
new FieldDef[]{
new IntegerFieldDef("id"),
new StringFieldDef("nome"),
new StringFieldDef("preco"),
new StringFieldDef("marca"),
new IntegerFieldDef("id_categoria")
}
);
MemoryProxy proxy = new PagingMemoryProxy(dado);
ArrayReader reader = new ArrayReader(recordDef);
Store store = new Store(proxy, reader);
store.load();
grid.setStore(store);
ColumnModel columnModel = new ColumnModel(columns);
grid.setColumnModel(columnModel);
grid.setFrame(true);
grid.setStripeRows(true);
grid.setTitle("Procurar dados");
grid.setWidth(720);
grid.setHeight(328);
Toolbar topToolbar = new Toolbar();
topToolbar.addFill();
grid.setTopToolbar(topToolbar);
GridSearchPlugin gridSearch = new GridSearchPlugin(GridSearchPlugin.TOP);
gridSearch.setMode(GridSearchPlugin.LOCAL);
gridSearch.setSearchText("Buscar");
grid.addPlugin(gridSearch);
grid.doLayout();
MessageBox.hide();
return grid;
}
public static native void abrirHtml(String url) /*-{
$wnd.open(url, '_blank');
}-*/;
}
JanelaTestes.java
package exemplo.teste.client;
import com.gwtext.client.widgets.Window;
public class JanelaTestes extends Window{
public JanelaTestes() {
// TODO Auto-generated constructor stub
}
}
gwtext.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
#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;
}
</style>
<title>GWT-Ext</title>
<!-- -->
<!-- Use normal html, such as style -->
<!-- -->
<style>
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}
</style>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic ui -->
<!-- -->
<body>
<!--add loading indicator while the app is being loaded-->
<div id="loading">
<div class="loading-indicator">
<img
/>GWT-Ext<br/>
<span id="loading-msg">Carregando estilos e imagens...</span></div>
</div>
<link rel="stylesheet" type="text/css" href="js/ext/resources/css/ext-all.css"/>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Carregando fontes...';</script>
<!--include the Ext Core API-->
<script type="text/javascript" src="js/ext/adapter/ext/ext-base.js"></script>
<!--include Ext -->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Carregando...';</script>
<script type="text/javascript" src="js/ext/ext-all.js"></script>
<script type="text/javascript" src="js/ext/source/locale/ext-lang-pt_BR.js"></script>
<!--include the application JS-->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Iniciando...';</script>
<script language='javascript' src='exemplo.teste.gwtext.nocache.js'></script>
<script type="text/javascript">Ext.get('loading').fadeOut({remove: true, duration:.25});</script>
</body>
</html>
GwtServiceImpl.java
package exemplo.teste.server;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import exemplo.teste.beans.CarregarDadosBean;
import exemplo.teste.client.Constantes;
import exemplo.teste.client.GwtExtService;
public class GwtExtServiceImpl extends RemoteServiceServlet implements GwtExtService {
public static String servletContext;
@Override
public void init() throws ServletException {
boolean isWebMode = getServletContext().getInitParameter(Constantes.GWT_MODE).equalsIgnoreCase(
Constantes.WEB_MODE);
System.setProperty("path.conexaoteste", isWebMode ? getServletContext().getRealPath("/") + "WEB-INF" + File.separator
+ "classes" + File.separator : this.getPathConTeste(System.getProperty("java.class.path").split(
File.pathSeparator)));
servletContext = getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "classes" + File.separator;
}
private String getPathConTeste(String[] array) {
String resp = null;
for (String pos : array) {
if (pos.contains(File.separator + "conec")) {
resp = pos;
break;
}
}
return resp;
}
public String[][] carregarDados() throws SQLException {
List<CarregarDadosBean> carrega = carregarDadosService();
String[][] retornos = new String[carrega.size()][5];
int k=0;
for(k=0;k<carrega.size();k++){
CarregarDadosBean carregarDadosBean = (CarregarDadosBean)carrega.get(k);
retornos[k] = new String[]{
carregarDadosBean.getId().toString(),
carregarDadosBean.getNome(),
carregarDadosBean.getPreco().toString(),
carregarDadosBean.getMarca(),
carregarDadosBean.getId_categoria().toString()
};
}
return retornos;
}
public static ArrayList><CarregarDadosBean> carregarDadosService() throws SQLException {
ArrayList<CarregarDadosBean> carregar = new ArrayList<CarregarDadosBean>();
ResultSet rs = carregamento();
while(rs.next()){
CarregarDadosBean carregarDadosBeanPop = popularCarregarDadosBean(rs);
carregar.add(carregarDadosBeanPop);
}
return carregar;
}
private static CarregarDadosBean popularCarregarDadosBean(ResultSet rs) throws SQLException {
CarregarDadosBean carregarDadosBean = new CarregarDadosBean();
carregarDadosBean.setId(rs.getInt("id"));
carregarDadosBean.setNome(rs.getString("nome"));
carregarDadosBean.setPreco(rs.getDouble("preco"));
carregarDadosBean.setMarca(rs.getString("marca"));
carregarDadosBean.setId_categoria(rs.getInt("id_categoria"));
return carregarDadosBean;
}
private static ResultSet carregamento() throws SQLException {
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres",
"postgres",
"postgres");
} catch (Exception e) {
System.out.println("Erro ao obter conexao via DriverManager: "
+ e.getMessage());
}
String sql = "SELECT * FROM produtos";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs;
}
}
RESULTADO