Boa tarde, estou começando a fazer uns testes utilizando FLEXIGRID com JSON, e tenho pesquisado se existe alguma dpcumentação sobre a FLEXIGRID e até o atual momento não encontrei, então conversando com amigos e lendo em alguns foruns estou desenvolvendo um protótico que pretendo inserir no framework da empresa que trabalho. Diferente dos outros post’s que vi aqui no GUJ, não utilizo VRaptor e tambem não pretendo. Acho que por isso que estou apanhando tanto. Bom para vocês entenderem melhor até onde ja cheguei oque eu fiz eu criei uma classe que irá acessar uma tabela e retornar um Json. Chama-se UsuarioModel
[code]import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.json.JSONException;
import org.json.JSONObject;
public class UsuarioModel {
Connection conn;
public UsuarioModel(Connection conn) {
this.conn = conn;
}
public static boolean isEmpty(String val){
return (val==null || “”.equals(val.trim()));
}
public int contarReg(String tipo, String parametro) throws SQLException{
int contador = 0;
String sql = “SELECT IdUsr " +
“FROM usuarios”;
if(!isEmpty(tipo) && !isEmpty(parametro))
sql += " WHERE “+tipo+” like '%”+parametro+"%’";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
contador++;
}
return contador;
}
public JSONObject listar(String tipo, String parametro) throws SQLException, JSONException{
String sql = “SELECT IdUsr,”
+ " usr,"
+ " NomeCompletoUsr "
+ " FROM Usuarios “;
if(!isEmpty(tipo)&& !isEmpty(parametro))
sql += " WHERE “+tipo+” like '%”+parametro+"%’";
PreparedStatement pstmt = conn.prepareStatement(sql);
int indice = 0;
ResultSet rs = pstmt.executeQuery();
JSONObject usuariosJson = new JSONObject();
while (rs.next()){
indice = 1;
JSONObject usuarioJson = new JSONObject();
usuarioJson.put(“id”, rs.getInt(indice));
usuarioJson.put(“cell”,
new Object[]{
rs.getInt(indice++),
rs.getString(indice++),
rs.getString(indice++)});
usuariosJson.append(“rows”, usuarioJson);
}
return usuariosJson;
}
}[/code]
Depois de criado essa classe, eu criei uma chamda FlexiGridJson que irá fazer a criação do Json corretamente para a grid.
import org.json.JSONException;
import org.json.JSONObject;
public class FlexiGridJson {
public static String criar(Integer pagina, Integer total, JSONObject registros){
JSONObject registrosJson = new JSONObject();
try {
registrosJson.put("page", pagina);
registrosJson.put("total", total);
//registrosJson.append("rows", registros);
registrosJson.put("rows",registros.getJSONArray("rows"));
} catch (JSONException ex) {
ex.printStackTrace();
}
return registrosJson.toString();
}
}
Bom por ultimo foi criado a classe que irá fazer o envio desse pacote a grid, chama-se UsuarioController
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ConnectionFactory;
import model.UsuarioModel;
import org.json.JSONException;
import util.FlexiGridJson;
public class UsuarioController extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
UsuarioModel usuarioModel = new UsuarioModel(ConnectionFactory.getInstance().connect());
String parametro = request.getParameter("query");
String tipo = request.getParameter("qtype");
try {
out.print(FlexiGridJson.criar(1, usuarioModel.contarReg(tipo,parametro), usuarioModel.listar(tipo,parametro)));
} catch (SQLException ex) {
ex.printStackTrace();
} catch (JSONException ex) {
ex.printStackTrace();
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Bom até ai tudo bem a grid aparece os registros, consegui fazer filtrar pelos campos que determinei blz, eu não to sabendo é fazer a páginação correta da grid nem utilizar a ordenação clicando no header dela, alguem tem ideia como faz isso? E outra pergunta o flexigrid faz agrupamento como o ext js ?
So pra completar o meu JSP ficou assim:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="biblioteca/flexigrid/lib/jquery/jquery.js"></script>
<script type="text/javascript" src="biblioteca/flexigrid/flexigrid.js"></script>
<link rel="stylesheet" type="text/css" href="biblioteca/flexigrid/css/flexigrid/flexigrid.css"/>
<style>
body
{
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
.flexigrid div.fbutton .add
{
background: url(biblioteca/flexigrid/css/images/add.png) no-repeat center left;
}
.flexigrid div.fbutton .delete
{
background: url(biblioteca/flexigrid/css/images/close.png) no-repeat center left;
}
</style>
</head>
<body>
<table id="grid01" style="display:none"></table>
<script type="text/javascript">
$("#grid01").flexigrid({
url: 'UsuarioController',
dataType: 'json',
colModel : [
{display: 'Codigo', name : 'Id', width : 40, sortable : true, align: 'center'},
{display: 'Login', name : 'Usr', width : 60, sortable : true, align: 'left'},
{display: 'Nome', name : 'Nome', width : 180, sortable : true, align: 'left'}
],
/* buttons : [
{name: 'Add', bclass: 'add', onpress : true},
{name: 'Delete', bclass: 'delete', onpress : true},
{separator: true}
],
*/
searchitems : [
{display: 'Codigo', name : 'IdUsr'},
{display: 'Nome', name : 'NomeCompletoUsr', isdefault: true}
],
sortname: "iso",
sortorder: "asc",
usepager: true,
singleSelect: true,
title: 'Grid Teste',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 700,
//onSubmit: addFormData,
height: 200
});
</script>
</body>
</html>
Espero que alguem possa me ajudar !!!
Abraço