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

martes, 31 de marzo de 2009

ComboBox remoto con GWT-EXT (json,jsp) con Java

Bueno supongamos que tenemos una tabla en alguna bd, y lo único que nos interesa es hacer un combobox que muestre un nombre y que tenga como value una clave:

sql:
select cvetpocit,nomtpocit from reftpocit

el modelo seria algo como esto:

/**
*
* @author isaac
*/
public class Citacion {

private String cve;
private String nombre;

public String getCve() {
return cve;
}
public void setCve(String cve) {
this.cve = cve;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}

el contenedor hecho con una conexion jdbc de java:


import conexion.connectionSelGWT;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import xxx.xxx.client.referencia.modelo.Citacion;

/**
*
* @author isaac
*/

public class ContenedorTpoCitacion {

private Connection conexion;
private Statement instruccion;

public ContenedorTpoCitacion() throws SQLException {
connectionSelGWT conectaBase = new connectionSelGWT();
conexion = conectaBase.conectBase();
}

public List<Citacion> getTpoCitacion() throws SQLException{
List<Citacion> list = new ArrayList<Citacion>();
String query = "select cvetpocit,nomtpocit from reftpocit";
instruccion = conexion.createStatement();
ResultSet resultados2 = instruccion.executeQuery(query);
while (resultados2.next()) {
Citacion citacion = new Citacion();
citacion.setCve(resultados2.getString(1));
citacion.setNombre(resultados2.getString(2));
list.add(citacion);
}
resultados2.close();
conexion.close();
return list;
}

}


Esta es clase de la conexion aunque pueden ocupar la suya, despues voy a hacer un ejemplo con hibernate:


import java.sql.*;
import java.util.Vector;


/**
* A Class class.
*


* @author Mew
*/


public class connectionSelGWT{

private Connection conexion;
public Connection conectBase(){
String URL = "jdbc:oracle:thin:@suip_o_localhost:1521:su_SID";
String userid = "su_usuario";
String password= "su_pass";
connect();
try {
conexion = DriverManager.getConnection(URL, userid, password);

}catch (SQLException E) {
return conexion=null;
}

return conexion;
}

}

El contenedor:

import conexion.connectionSelGWT;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import xxxx.xxx.referencias.modelo.Citacion;

/**
*
* @author isaac
*/
public class ContenedorTpoCitacion {
private Connection conexion;
private Statement instruccion;

public ContenedorTpoCitacion() throws SQLException {
connectionSelGWT conectaBase = new connectionSelGWT();
conexion = conectaBase.conectBase();

}

public List getTpoCitacion() throws SQLException{
List list = new ArrayList();

String query = "select cvetpocit,nomtpocit from reftpocit";

instruccion = conexion.createStatement();



ResultSet resultados2 = instruccion.executeQuery(query);
while (resultados2.next()) {
Citacion citacion = new Citacion();
citacion.setCve(resultados2.getString(1));
citacion.setNombre(resultados2.getString(2));
list.add(citacion);

}
resultados2.close();
conexion.close();
return list;
}

}

La clase que crea la estructura del json para la vista:



import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import xxx.xxx.client.referencia.modelo.Citacion;

/**
*
* @author isaac
*/
public class JsonCitacion {

public String getTpsCitacion() throws JSONException, SQLException{
ContenedorTpoCitacion con = new ContenedorTpoCitacion();
List<Citacion> list = con.getTpoCitacion();
JSONObject jsonObj = new JSONObject();
jsonObj.put("totalCount",list.size()+"");
JSONArray array = new JSONArray();
for(Citacion ci:list){
JSONObject jsonDatos = new JSONObject();
jsonDatos.put("cve",ci.getCve());
jsonDatos.put("nombre",ci.getNombre());
array.put(jsonDatos);
}

jsonObj.put("datos",array);
return jsonObj.toString();
}

public static void main(String[] args) {
JsonCitacion json = new JsonCitacion();

try {

System.out.println(json.getTpsCitacion());

} catch (JSONException ex) {

Logger.getLogger(JsonCitacion.class.getName()).log(Level.SEVERE, null, ex);

} catch (SQLException ex) {
Logger.getLogger(JsonCitacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


la estructura que recibiria el combo de GWT-EXT seria la siguiente:

{"totalCount":"2","datos":[{"nombre":"Periodica","cve":"1"},{"nombre":"No Periodica","cve":"2"}]}

* las xxx son paquetes con nombre de mi trabajo pero bien le pueden poner otro nombre, es para que no vean donde trabajo jijijiji+++++.

el jsp llamado jsoncitas.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="xxx.xxxx.referencias.mc.JsonCitacion"%>
<%@page import="java.sql.SQLException"%>
<%@page import="org.json.*"%>



<% JsonCitacion json = new JsonCitacion(); try { out.print(json.getTpsCitacion()); } catch (JSONException ex) { } catch (SQLException ex) { } %>

y por ultimo el combox solo pondre el codigo del combo, solo lo tienen que agregar a un panel y listo:

HttpProxy dataProxy = new HttpProxy("jsoncitas.jsp");
RecordDef recordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("cve", "cve"),
new StringFieldDef("nombre", "nombre")
});
JsonReader reader4 = new JsonReader(recordDef);
reader4.setRoot("datos");
reader4.setTotalProperty("totalCount");
Store store5 = new Store(dataProxy, reader4);
store5.load();

final ComboBox cbCitacion = new ComboBox();
cbCitacion.setStore(store5);
cbCitacion.setForceSelection(true);
cbCitacion.setMinChars(1);
cbCitacion.setFieldLabel("Tipo citación");
cbCitacion.setDisplayField("nombre");
cbCitacion.setMode(ComboBox.REMOTE);
cbCitacion.setTriggerAction(ComboBox.ALL);
cbCitacion.setEmptyText("Enter tpo citación");
cbCitacion.setLoadingText("Searching...");
cbCitacion.setTypeAhead(true);
cbCitacion.setSelectOnFocus(true);
cbCitacion.setWidth(200);
cbCitacion.setHideTrigger(false);
cbCitacion.addListener(new ComboBoxListenerAdapter() {

public void onSelect(ComboBox comboBox, Record record, int index) {

String tpoCita = Integer.parseInt(record.getAsString("cve"));
MessageBox.alert("hola "+tpoCita);
}
});

y por ultimo les debe quedar algo como esto:


viernes, 23 de enero de 2009

GWT-EXT, Combo box, remoto con jsp's

Lo primero que necesitamos es crear HttpProxy y un store con la estructura de nuestro json, aunque por default este metodo se encarga de mandarle parametros con query, para este ejemplo no los tomaremos

HttpProxy dataProxy = new HttpProxy("EvaluacionJson.jsp?respuesta=revista");
RecordDef recordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("clave", "clave"),
new StringFieldDef("name", "name"),});

JsonReader reader = new JsonReader(recordDef);
reader.setRoot("datos");
reader.setTotalProperty("totalCount");

Store store = new Store(dataProxy, reader, true);
store.reload();

ComboBox cbRevista = new ComboBox("Revista");

cbRevista.setStore(store);
cbRevista.setTitle("Revistas existentes");
cbRevista.setDisplayField("name");
cbRevista.setId("clave");
cbRevista.setMode(ComboBox.REMOTE);
cbRevista.setTriggerAction(ComboBox.ALL);
cbRevista.setLoadingText("Buscando...");
cbRevista.setWidth(300);
cbRevista.setEmptyText("-SELECCIONE UNA REVISTA-");
cbRevista.addListener(new ComboBoxListenerAdapter() {

public void onSelect(ComboBox comboBox, Record record, int index) {


String cveRev = record.getAsString("clave");

}
});

Podemos agregar el combo a un formpanel o aun panel, despues esta el listener del combo que escucha los eventos del combo con record.getAsString("clave") extraen el clave del combo.

El jsp :

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="org.siir.json.JsonEvaluacion"%>
<%@page import="org.json.*"%>

<%

String respuesta = request.getParameter("respuesta");

if(respuesta.equals("revista")){
JsonEvaluacion jsonEvaluacion= new JsonEvaluacion();
String stringJson="";
try {
stringJson = jsonEvaluacion.obtenRevistasCandidatas();
} catch (JSONException ex) {
out.print("{\"totalCount\":0,\"datos\":[]}");
}
out.println(stringJson);
}


%>

el json:

package org.siir.json;

import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.siir.client.modelo.hemeroteca.RevistaExistente;
import org.siir.contenedor.ContenedorRevistaCandidata;

/**
*
* @author isaac
*/
public class JsonEvaluacion {

public String obtenRevistasCandidatas() throws JSONException{
ContenedorRevistaCandidata contenedorRev= new ContenedorRevistaCandidata();
List listRev = contenedorRev.getAllRevistaExistente();
JSONObject jsonObj = new JSONObject();
jsonObj.put("totalCount", listRev.size()+"");
JSONArray array = new JSONArray();


for(RevistaExistente rev:listRev){

JSONObject jsonDatos = new JSONObject();

jsonDatos.put("name",rev.getNombreRevista());
jsonDatos.put("clave",rev.getClave()+"");


array.put(jsonDatos);
}

jsonObj.put("datos",array);


return jsonObj.toString();


}


public static void main(String[] args) throws JSONException {
JsonEvaluacion jsonEvaluacion= new JsonEvaluacion();
System.out.println(jsonEvaluacion.obtenRevistasCandidatas());
}


}
el contenedor: claro esta tienen que iniciar una session hibernate, y todo ese choro, pueden reemplazar todo esto por un contenedor con sql, y con resultset construllen la lista de RevistaExistente

public List getAllRevistaExistente() {
Session s = sF.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from RevistaExistente p where p.estadoRevista = 1" );
List respuesta=q.list();
tx.commit();
s.close();
return respuesta;
}

el modelo:

public class RevistaExistente implements IsSerializable {
private Long clave;
private String nombreRevista;

con sus getters y setters...