Foros del Web » Programación para mayores de 30 ;) » Java »

llenar JTree con base de datos en web app

Estas en el tema de llenar JTree con base de datos en web app en el foro de Java en Foros del Web. hola a todos Bueno estoy tratando de hacer una vista de árbol con JTree pero con información que viene desde una base de datos; la ...
  #1 (permalink)  
Antiguo 31/05/2010, 13:48
 
Fecha de Ingreso: mayo-2010
Mensajes: 27
Antigüedad: 14 años
Puntos: 1
Mensaje llenar JTree con base de datos en web app

hola a todos

Bueno estoy tratando de hacer una vista de árbol con JTree pero con información que viene desde una base de datos; la tabla de donde extraigo los datos para el árbol tienen los campos id_padre, id_hijo. Cada hijo puede tener varios hijos.

Intente hacerlo usando el método DefaultMutableTreeNode, pero no me funcionó por el parámetro del índice. Soy nueva usando JTrees, he revisado este enlace

http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#create

pero la verdad es que no lo entiendo muy bien.


Mi pregunta es, ¿De qué manera puedo llenar los datos en el JTree y que se muestren en una aplicación web mediante un botón? ¿Es esto posible?

Muchas gracias de antemano.
  #2 (permalink)  
Antiguo 02/06/2010, 09:47
 
Fecha de Ingreso: mayo-2010
Mensajes: 27
Antigüedad: 14 años
Puntos: 1
Respuesta: llenar JTree con base de datos en web app

Bueno, he encontrado algo en
http://www.easywayserver.com/forum/viewtopic.php?t=41

pero no se por qué me sale el error "The resultSet is closed "

este es el código que tengo, trato de conectarlo a una bd Firebird donde ya tengo la tabla Nodestable.

Código PHP:
CREATE TABLE  nodestable (
  
NodeID integer NOT NULL,
  
Name varchar(45) ,
  
IsFolder integer NOT NULL,
  
ParentID integer NOT NULL,
  
Link varchar(45NOT NULL,
  
Llevel  integer,
  
PRIMARY KEY  (NodeID)

Este es el código del JSP. Sé que no es muy elegante poner todo junto(Conexión, modelo y vista :( ) pero tengo que empezar por algo.

Código PHP:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.util.StringTokenizer,java.util.*,java.text.*" errorPage="" %>

<%

         
Connection conn =null;
         Class.
forName("org.firebirdsql.jdbc.FBDriver");
         try{
           
conn DriverManager.getConnection("jdbc:firebirdsql://localhost:3050//home/pg/pgdb.fdb""SYSDBA""60011600");
         
String tempNodeID=nullconv(request.getParameter("NodeID"));
         
int tempdownline=nullIntconv(nullconv(request.getParameter("downline")));
         
setConnection(conn,out,tempNodeID,tempdownline);
         }
         catch(
Exception e)
         {
           
e.printStackTrace();
         }
%>

<%!
public 
String nullconv(String str)
{
   if(
str==null)
      
str="";
   else if(
str.equalsIgnoreCase("null"))
      
str="";
   else if((
str.trim()).equals(""))
      
str="";
   return 
str;
}
public 
int nullIntconv(String inv)
   {
      if(
inv==null)
      {
         
inv="0";
      }
      else if((
inv.trim()).equals("null"))
      {
         
inv="0";
      }
      else if(
inv.equals(""))
      {
         
inv="0";
      }

      return 
Integer.parseInt(inv);
   }


       
Connection con=null;

      
PreparedStatement pstmt null;
      
PreparedStatement pstmt1 null;

      
ResultSet rs null;
      
ResultSet rs1 null;

      
JspWriter out=null;
      
String   NodeID =  "1";
       
int downline 0;

   public 
void setConnection(Connection con,JspWriter ot,String rq,int dwline)
   {
      
this.con=con;
      try{
      
this.out=ot;
      
NodeID=rq;
      
downline=dwline;

       if(
NodeID.equals(""))
         {
          
NodeID="1";  ///////////////////// change this according to your requirement
         
}
         if(
downline==0)
         {
          
downline=20;   ////////////////////// this is for advance requirement should use according to your requirement
         
}
      }
      catch(
Exception e)
      {
         
System.out.println("IO error :"+e);
      }

    }


   public 
void outputJavascriptForRoot()
   {

      
String queryString =null;

      
queryString ="SELECT NodeID, Name, IsFolder, ParentID, Link, Llevel FROM NodesTable WHERE (NodeID='" NodeID +"')";
      try{

      
pstmt=con.prepareStatement(queryString);
      
rs=pstmt.executeQuery();

      
// It should return one and one only
      
while (rs.next())
      {
        
out.print("foldersTree = gFld('<i>tree</i>')" "\n");
        
out.print("web" rs.getString("NodeID") + " = insFld(foldersTree, gFld('" rs.getString("Name") + "[" rs.getString("NodeID") + "]"  "','tree.jsp?distibutorid=" rs.getString("NodeID") + "&downline="+downline+"'))" "\n");
        
outputJavascriptForSubFolder(Integer.parseInt(rs.getString("NodeID")), rs.getString("Name"),"web" rs.getString("NodeID"), rs.getString("Link"), downline);
      }

      
// close the DataReader and Connection



      
}
      catch(
SQLException ex)
      {
        
System.out.println("sqll eroror :"+ex);
       }
       catch(
Exception e)
       {
          
System.out.println("error :"+e);
       }
   }


 public 
void outputJavascriptForSubFolder(int folderIdString NameString fNameString Linkint downline)
   {

   try{
      
PreparedStatement psQueryString null;
      
ResultSet rsqueryString null;
      
String queryString1 ="SELECT NodeID, Name, IsFolder, ParentID, Link FROM NodesTable WHERE ((ParentID=" folderId ") AND (IsFolder=1) AND Llevel<=" downline ") ORDER BY Name";
      
psQueryString=con.prepareStatement(queryString1);
      
rsqueryString=psQueryString.executeQuery();


      
// iterate through the rows in the Nodes table
         
while(rsqueryString.next())
         {
         
out.print("web" rsqueryString.getString("NodeID") + "=insFld(" fName ",gFld('" rsqueryString.getString("Name") + "[" rsqueryString.getString("NodeID") + "]','tree.jsp?NodeID="+rsqueryString.getString("NodeID")+"&downline="+downline+"'))  " "\n" );
         
outputJavascriptForSubFolder(Integer.parseInt(rsqueryString.getString("NodeID")),rsqueryString.getString("Name"),"web" rsqueryString.getString("NodeID"),rsqueryString.getString("Link"),downline);
         }
      
psQueryString.close();
      
rsqueryString.close();
     }
   catch(
Exception e)
      {
        
System.out.println(e);
      }
   }

%>

<
html>
<
head>

<
title>Tree from database</title>

<
style type="text/css">
   
BODY {background-colorwhite}
   
TD {font-size10pt;
       
font-familyverdana,helvetica;
      
text-decorationnone;
      
white-space:nowrap;}
   
A  {text-decorationnone;
       
colorblack}
</
style>

<!-- As 
in a client-side built treeall the tree infrastructure is put in place
     within the HEAD block
but the actual tree rendering is trigered within the
     BODY 
-->

<!-- 
Code for browser detection -->
<
script language="javascript" src="ua.js"></script>
<script language="javascript" src="ftiens4.js"></script>
<!-- Execution of the code that actually builds the specific tree.
     The variable foldersTree creates its structure with calls to
    gFld, insFld, and insDoc -->
<script language="javascript">
USETEXTLINKS = 1
STARTALLOPEN = 1
PRESERVESTATE = 1
ICONPATH = ''
HIGHLIGHT = 1
<%
outputJavascriptForRoot();
%>


// Load a page as if a node on the tree was clicked (synchronize frames)
// (Highlights selection if highlight is available.)
function loadSynchPage(xID)
{
   var folderObj;
   docObj = parent.treeframe.findObj(xID);
   docObj.forceOpeningOfAncestorFolders();
   parent.treeframe.clickOnLink(xID,docObj.link,'basefrm');

    //Scroll the tree window to show the selected node
    //Other code in these functions needs to be changed to work with
    //frameless pages, but this code should, I think, simply be removed
    if (typeof parent.treeframe.document.body != "undefined") //scroll doesn work with NS4, for example
        parent.treeframe.document.body.scrollTop=docObj.navObj.offsetTop
}
</script>
</head>

<body topmargin=16 marginheight=16>

<!-- By removing the follwoing code you are violating your user agreement.
     Corporate users or any others that want to remove the link should check
    the online FAQ for instructions on how to obtain a version without the link -->
<!-- Removing this link will make the script stop from working -->
<div style="position:absolute; top:0; left:0; "><table border=0><tr><td><font size=-2><a style="font-size:7pt;text-decoration:none;color:silver" href="http://www.treemenu.net/" target=_blank>JavaScript Tree Menu</a></font></td></tr></table></div>

<!-- Build the browser's objects and display default view of the
     tree. -->
<script language="javascript">
initializeDocument()
//Click the Parakeet link
loadSynchPage(11)
</script>
<noscript>
A tree for site navigation will open here if you enable JavaScript in your browser.
</noscript>
</body>
</html> 
Al correrlo, me muestra tres veces la excepción de la base de datos "ResultSet is closed"

¿Alguna idea?
Muchas gracias por adelantado.
  #3 (permalink)  
Antiguo 06/06/2010, 05:22
 
Fecha de Ingreso: febrero-2010
Mensajes: 128
Antigüedad: 14 años, 2 meses
Puntos: 3
Respuesta: llenar JTree con base de datos en web app

nunca he trabajado con Jtree, pero espero que tengas suerte

Si te puedo decir que si el resultset está cerrado es porque ha fallado en algo el acceso a la base de datos.
Sin mirar el código de tu web, los errores posiblemente sean que la select esté mal formulada, deberías probar lo que te devuelve ejecutandola directamente contra la base de datos. o sino quizás tengas problemas con la conexión a la base de datos, quizás el driver de la base de datos o usuarios y contraseña incorrectos, no conozco firebird, pero no he visto que utilizes ningún credencial para conectarte.

Suerte
  #4 (permalink)  
Antiguo 07/06/2010, 17:53
 
Fecha de Ingreso: mayo-2010
Mensajes: 27
Antigüedad: 14 años
Puntos: 1
Respuesta: llenar JTree con base de datos en web app

Hola
gracias por contestar.
Bueno, ya he probado la consulta y me arroja normalmente los resultados.
La conexión a la base de datos la probé con otra clase y funciona normalmente. ¿A qué te refieres con "credencial"?

He probado cerrando el resultset en el método de arriba pero sale el mismo problema, "The resultset is closed"

Gracias por su ayuda

Etiquetas: llenar, apps
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:19.