miércoles, 25 de marzo de 2009

grid en jquery con jsp y json (java)

Bueno un amigo me dijo que le ayuda a hacer un grid con jquery me paso el link de donde descargarlo y estaba en php pero yo lo voy a hecer en java con la ayuda de json (deben descargar el jar de json,ok) y la repuesta se hara con un jsp.
de este link lo pueden descargar http://www.trirand.com/blog/?page_id=6

Bueno primero creamos un proyecto web en cualquier IDE yo ocupe Netbeans, para ese ejemplo lo llamaremos Cliente (Es un clásico):



Como un tip cuando vayan a crear un bean con sus getters y setters no es necesario crear cada get y set por cada atributo netbeans milagrosamente nos ayuda (jijiji+++)



solo den click derecho y después insert code y despues crear getter y setter

Bueno esto los ayudara mucho pero de todas maneras pongo el código:

package modelo;

import java.util.Date;

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

private String cve;
private Date date;
private String nombre;
private double cantidad;
private double tax;
private double total;
private String notas;

public double getCantidad() {
return cantidad;
}

public void setCantidad(double cantidad) {
this.cantidad = cantidad;
}

public String getCve() {
return cve;
}

public void setCve(String cve) {
this.cve = cve;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getNombre() {
return nombre;
}

public void setNombre(String nombre) {
this.nombre = nombre;
}

public String getNotas() {
return notas;
}

public void setNotas(String notas) {
this.notas = notas;
}

public double getTax() {
return tax;
}

public void setTax(double tax) {
this.tax = tax;
}

public double getTotal() {
return total;
}

public void setTotal(double total) {
this.total = total;
}




}

depues para crear el json el codigo es el siguiente: bueno antes la estructura del json que debemos crear es la siguiente:

{"total":"1","page":"1","rows":[{"id":"1","cell":["1","Wed Mar 25 15:16:35 CST 2009","Josue Isaac 0"
,"100.0","10.0","110.0","Salva al mundo usa JAVA 0"]},{"id":"2","cell":["2","Wed Mar 25 15:16:35 CST
2009","Josue Isaac 1","101.0","11.0","112.0","Salva al mundo usa JAVA 1"]},{"id":"3","cell":["3","Wed
Mar 25 15:16:35 CST 2009","Josue Isaac 2","102.0","12.0","114.0","Salva al mundo usa JAVA 2"]}],"records"
:"3"}

Pueden crear esta estructura con su base datos, pero no entrare en detalles:

package json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import modelo.Cliente;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public static String construlleJson() throws JSONException{
List listCliente = new ArrayList();
for(int i=0;i < cliente =" new">
cliente.setCve((i+1)+"");
cliente.setDate(new Date());
cliente.setNombre("Josue Isaac "+i);
cliente.setCantidad(100+i);
cliente.setTax(10+i);
cliente.setTotal(cliente.getCantidad()+cliente.getTax());
cliente.setNotas("Salva al mundo usa JAVA "+i);
listCliente.add(cliente);
}

JSONObject jsonObj = new JSONObject();
jsonObj.put("page","1");
jsonObj.put("total","1");
jsonObj.put("records", listCliente.size()+"");

JSONArray array = new JSONArray();
for(Cliente cliente:listCliente){
JSONObject jsonDatos= new JSONObject();
jsonDatos.put("id",cliente.getCve());
JSONArray arrayCell = new JSONArray();
arrayCell.put(cliente.getCve());
arrayCell.put(cliente.getDate());
arrayCell.put(cliente.getNombre());
arrayCell.put(cliente.getCantidad()+"");
arrayCell.put(cliente.getTax()+"");
arrayCell.put(cliente.getTotal()+"");
arrayCell.put(cliente.getNotas()+"");

jsonDatos.put("cell",arrayCell);

array.put(jsonDatos);
}
jsonObj.put("rows",array);


return jsonObj.toString();
}

public static void main(String[] args) throws JSONException {
System.out.println(Json.construlleJson());
}

}

Las lineas en rojo es donde creo una lista de clientes la cual servirá para crear la estructura del json pero ustedes pueden crear un cotenedor que les retorne una lista de Clientes, o con lo quieran llenar su grid, desde su bd. La linea en azul es el objeto principal json y el que retornamos al final, el código de jsp es este:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="json.Json"%>
<%@page import="org.json.*"%>
<%
String stringJson="";
try {
stringJson = Json.construlleJson();
} catch (JSONException ex) {
out.print("{\"totalCount\":0,\"datos\":[]}");
}
out.println(stringJson);
%>

el html o jsp que contrenda el grid de jquery tendra lo siguiente:

<html> <head> <title>jqGrid Demo</title>
<link rel="stylesheet" type="text/css" media="screen" href="eder/themes/basic/grid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="eder/themes/jqModal.css" />
<script src="eder/jquery.js" type="text/javascript"></script>
<script src="eder/jquery.jqGrid.js" type="text/javascript"></script>
<script src="eder/js/jqModal.js" type="text/javascript"></script>
<script src="eder/js/jqDnR.js" type="text/javascript"></script>
<script type="text/javascript">


function load()
{
jQuery("#list2").jqGrid({ url:'json.jsp', datatype: "json", colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:55}, {name:'invdate',index:'invdate', width:90}, {name:'name',index:'name asc, invdate', width:100}, {name:'amount',index:'amount', width:80, align:"right"}, {name:'tax',index:'tax', width:80, align:"right"}, {name:'total',index:'total', width:80,align:"right"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:10, rowList:[10,20,30], imgpath: 'eder/themes/basic/images', pager: jQuery('#pager2'), sortname: 'id', viewrecords: true, sortorder: "desc", caption:"JSON Example" }).navGrid('#pager2',{edit:false,add:false,del:false});
}



</script>
</head>
<body onload="load()">
<table id="list2" class="scroll"></table>
<div id="pager2" class="scroll" style="text-align:center;"></div>
</body>
</html>


la estructura del proyecto seria la siguiente:


Al final el grid se debe paser a este:



Adios...

1 comentario:

Anónimo dijo...

no entiendo, me tira mil errores, importe las librerias necesariass,,, seguro q esa bien tu proyecto?'? podrias subir el folder d netbeans???