package paquetes.controlador;
import paquetes.modelo.Contacto;
import paquetes.modelo.Model;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.io.PrintWriter;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class ListarContacto extends Action {
public void run()throws ServletException, IOException{
JSONObject respuesta=new JSONObject();
try {
respuesta=aJson();
}catch (Exception ex) {
throw new ServletException(ex.toString());
}
escribir(respuesta);
}
public JSONObject aJson()throws Exception{
JSONObject respuesta=new JSONObject();
JSONArray arreglo=new JSONArray();
try {
Model model= new Model();
ArrayList lista=model.listaContacto();
for (int i = 0; i
arreglo.put(i,Contacto.load(lista.get(i)));
}
}catch (Exception ex) {
respuesta.put("mensaje",ex.toString());
respuesta.put("tipo","Error");
return respuesta;
}
respuesta.put("success",true);
respuesta.put("rows",arreglo);
return respuesta;
}
public void escribir(JSONObject texto)throws IOException{
String cb = request.getParameter("callback");
boolean scriptTag = false;
if (cb != null) {
scriptTag = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
PrintWriter out = response.getWriter();
response.getWriter().print(texto);
}
}
lo mas importante es:
en el metodo aJson
JSONArray arreglo=new JSONArray(); creamos un JSONArray y recorremos la lista de objetos o datos traidos de la BD y los guardamos en el array que automaticamente con el metodo que creamos en el bean el lo convierte.
Model model= new Model(); //conexion a la BD
ArrayList lista=model.listaContacto(); //datos de la BD
for (int i = 0; i
arreglo.put(i,Contacto.load(lista.get(i)));//ponemos lo que estaba en la bd en el array
}
respuesta.put("success",true);//y el proceso finalizo correctamente
respuesta.put("rows",arreglo);//ponemos la info en lo que vamos a escribir
en el metodo escribir:
escogemos que tipo de respuesta será si javascript o json, y luego obtenemos el medio para escribir y escribimos.
No hay comentarios:
Publicar un comentario
DEJA UN COMENTARIO...
SI NO LO DICES NO LO SE