Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    77

    PROBLEMI CON XML element.addContent(....) non funziona

    Ho un problema che non riesco a risolvere. da un html con un form per inserire i dati di chi si deve registrare al sito dall'action di tale form viene lanciata una servlet.
    La servlet verifica se il file registrati.xml esiste, se non esiste lo crea e aggiunge il registrato che ha avuto la fortuna di essere stato il primo a registrarsi al sito.
    Se il file invece esiste non fa altro che caricarlo in memoria analizzarlo per vedere se un registrato ha la password uguale a quella dell'utente che sta tentando di registrarsi, se uno ce la uguale allora comunica che la registrazione è fallita causa duplicazione pasword altrimenti agiunge il nuovo registyrato allla struttura ad albero del documento e poi riscrive il file.
    Funziona tutto per il primo utente che si registra (viene creato registrati.xml con il primo registrato - c'è perchè ho verificato) poi appena tento di aggiungere altri registrati mi dice che

    org.jdom.IllegalAddException: The Content already has an existing parent "registrati"
    org.jdom.ContentList.add(ContentList.java:218)
    org.jdom.ContentList.add(ContentList.java:140)
    java.util.AbstractList.add(AbstractList.java:89)
    org.jdom.Element.addContent(Element.java:809)
    registrazione.aggiungiRegistrato(registrazione.jav a:67)
    registrazione.doPost(registrazione.java:144)
    javax.servlet.http.HttpServlet.service(HttpServlet .java:710)
    javax.servlet.http.HttpServlet.service(HttpServlet .java:803)


    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.10 logs.

    La struttura del registrati.xml è questa
    codice:
    <?xml version="1.0" encoding="UTF-8"?>
    <registrati>
    <registrato password="p" username="p" ruolo="generico">
    <nome>p</nome>
    <cognome>p</cognome>
    <via>p</via>
    <numciv>p</numciv>
    <city>p</city><area/>
    <telefono>p</telefono>
    <provincia>pp</provincia>
    <cap>p</cap>
    <nazione>p</nazione>
    <professione>pp</professione>
    <data_di_nascita>
    <giorno />
    <mese />
    <anno />
    </data_di_nascita>
    </registrato>
    </registrati>
    MENTRE LA SERVLET è QUESTA:
    codice:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.io.File;
    import java.util.*;
    import java.text.*;
    import org.jdom.*;
    import org.jdom.input.SAXBuilder;
    import org.jdom.output.XMLOutputter;
    import java.util.Iterator;
    import java.util.List;
    				
    public class registrazione extends HttpServlet{
    	StringBuffer buf = new StringBuffer();
    	Document documento = null;
    	Element elementoRegistrati;
    	Element registrato = new Element("registrato");
    	String nome,cognome,via,numciv,città,area,telefono,provincia,cap,nazione,professione,giorno_nascita,mese_nascita,anno_nascita,password_inviata,username_inviato;	
    	public void aggiungiRegistrato(){
    		Element element_nome = new Element("nome");
    		Element element_cognome = new Element("cognome");
    		Element element_via = new Element("via");
    		Element element_numciv = new Element("numciv");
    		Element element_city = new Element("city");
    		Element element_area = new Element("area");
    		Element element_telefono = new Element("telefono");
    		Element element_provincia = new Element("provincia");
    		Element element_cap = new Element("cap");
    		Element element_nazione = new Element("nazione");
    		Element element_professione = new Element("professione");
    		Element element_giorno = new Element("giorno");
    		Element element_mese = new Element("mese");
    		Element element_anno = new Element("anno");
    		Element nascita = new Element("data_di_nascita");
    		element_nome.setText(nome);
    		element_cognome.setText(cognome);
    		element_via.setText(via);
    		element_numciv.setText(numciv);
    		element_city.setText(città);
    		element_area.setText(area);
    		element_telefono.setText(telefono);
    		element_provincia.setText(provincia);
    		element_cap.setText(cap);
    		element_nazione.setText(nazione);
    		element_professione.setText(professione);
    		element_giorno.setText(giorno_nascita);
    		element_mese.setText(mese_nascita);
    		element_anno.setText(anno_nascita);
    		nascita.addContent(element_giorno);
    		nascita.addContent(element_mese);
    		nascita.addContent(element_anno);
    		registrato.addContent(element_nome);
    		registrato.addContent(element_cognome);
    		registrato.addContent(element_via);
    		registrato.addContent(element_numciv);
    		registrato.addContent(element_city);
    		registrato.addContent(element_area);	
    		registrato.addContent(element_telefono);
    		registrato.addContent(element_provincia);
    		registrato.addContent(element_cap);
    		registrato.addContent(element_nazione);
    		registrato.addContent(element_professione);
    		registrato.addContent(nascita);
    		registrato.setAttribute("password",password_inviata);
    		registrato.setAttribute("username",username_inviato);
    		registrato.setAttribute("ruolo","generico");	
    		elementoRegistrati.addContent(registrato);
    	}
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		response.setContentType("text/html");
    		PrintWriter responseOutput = response.getWriter();
    		String controllo = new String("ok");
    		//RECUPERO LE INFORMAZIONI INVIATE DAL FORM
    		nome = request.getParameter("nome");
    		cognome = request.getParameter("cognome");
    		via = request.getParameter("via");
    		numciv =request.getParameter("numciv");
    		città =request.getParameter("città");
    		area =request.getParameter("area");
    		telefono =request.getParameter("telefono");
    		provincia =request.getParameter("provincia");
    		cap =request.getParameter("cap");
    		nazione =request.getParameter("nazione");
    		professione =request.getParameter("professione");
    		giorno_nascita = request.getParameter("giorno_nascita");
    		mese_nascita = request.getParameter("mese_nascita");
    		anno_nascita = request.getParameter("anno_nascita");
    		password_inviata = request.getParameter("password_registrazione");
    		username_inviato = request.getParameter("username_registrazione");		
    		//CONTROLLO SE ESISTE GIA' UN FILE .XML CHE SI CHIAMA REGISTRATI
    		String path = new String ("../webapps/restaurants/xml/registrati.xml");
    		File file = new File(path);
    		//SE IL FILE NON ESISTE LO CREO E GLI AGGIUNGO L'ELEMENTO RADICE IL PRIMO REGISTRATO
    		if (!file.exists()){
    			file.createNewFile();
    			elementoRegistrati = new Element("registrati");
    			//AGGIUNGO IL REGISTARTO CHE RISULTA IL PRIMO DATO CHE IL FILE REGISTRATI.XML NON ESISTEVA
    			aggiungiRegistrato();
    			//SCRIVO IL DOCUMENT NEL FILE		
    			documento = new Document(elementoRegistrati);
    			XMLOutputter xmlOutputter = new XMLOutputter();
    			try{
       				FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); 
       				xmlOutputter.output(documento, fileOutputStream);
     			}
    	 		catch (FileNotFoundException ex){
       				System.err.println(ex);
     			}
    	 		catch (IOException ex){
       				System.err.println(ex);
     			}
    		}
    		else{
    			//SE IL FILE ESISTE LO CARICO IN MEMORIA
     			SAXBuilder saxBuilder = new SAXBuilder();
    			try{
       				documento = saxBuilder.build(new File(path)); 
     			}
     			catch (JDOMException ex){
       				System.err.println(ex);
    			}
    	 		catch (IOException ex){
       				System.err.println(ex);
     			}					
    			//POI UNA VOLTA CARICATO CONTROLLO CHE NON CI SIA GIA' UN REGISTRATO CON TALE LOGIN E SE NON C'è INSERISCO IL NUOVO REGISTRATO ALTRIMENTI GLI DICO DI CAMBIARE LOGIN
    			elementoRegistrati = documento.getRootElement(); 
    			List lista_registrati = elementoRegistrati.getChildren();
    			// ottengo un iteratore alla lista chiamando il metodo iterator() di Collection (essendo una list una collection) 
     			Iterator iteratore = lista_registrati.iterator();
    			while (iteratore.hasNext())
     			{ 
       				// ottengo l'elemento corrente chiamando next() sull'iteratore 
       				Element registrato_corrente = (Element)iteratore.next(); 
    				String username = registrato_corrente.getAttributeValue("username");
    				String password = registrato_corrente.getAttributeValue("password");
    				if (password_inviata.equals(password)){
    					buf.append("Password già presente, sceglierla diversamente");
    					controllo = new String("ko");
    					break;
    				}
     			}
    			if (controllo.equals("ok")){
    				//RISCRIVO L'INTERO DOCUMENTO NEL FILE XML DOPO AVER AGGIUNTO IL REGISTRATO
    				aggiungiRegistrato();
    				XMLOutputter xmlOutputter = new XMLOutputter();
     				//IL METODO SEGUENTE Format.getPrettyFormat() SERVE PER SCRIVERE SUL FILE XML IN MODO BEN FORMATTATO CON GLI A CAPO E LE INDENTAZIONI PER OGNI ELEMENTO, MA NON ME LO ACCETTA
    				//xmlOutputter.setFormat(Format.getPrettyFormat());
        				try{
       					FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); 
       					xmlOutputter.output(documento, fileOutputStream);
     				}
    		 		catch (FileNotFoundException ex){
       					System.err.println(ex);
     				}
    		 		catch (IOException ex){
       					System.err.println(ex);
     				}
    			}			
    		}
    		responseOutput.println(buf.toString());
    		responseOutput.close();
    	}
    }

  2. #2
    Il problema sta in questa riga:

    codice:
    Element registrato = new Element("registrato");
    Infatti, definendo l'elemento 'registrato' come variabile d'istanza, utilizzerai lo stesso elemento per tutte le chiamate; questo impedisce la creazione corretta del documento XML, in quanto un elemento può avere un solo padre, e appena tenti di inserirlo una seconda volta, ti viene dato l'errore.
    La soluzione è semplice: basta spostare l'istruzione all'interno del metodo aggiungiRegistrato, in modo da creare un nuovo elemento per ogni chiamata.

    Ciao,

  3. #3
    Utente di HTML.it
    Registrato dal
    Sep 2005
    Messaggi
    77
    GRAZIE MILLE EFFETTIVAMENTE ERA BANALE, MA ALLE PRIME ARMI PENSO CHE QUESTE COSE è POSSIBILE NON VEDERLE?!?!?!??!
    Spero che con l'esperienza il mio intuito si specializzi un pò di più nel frattempo mi scrivo in un file txt degli appunti a questi casi pratici che mi capitano da rileggere ogni tanto per ricordarmi un pò le soluzioni che si devono prendere...
    COMUNQUE TI RINGRAZIO ANCORA CIAO LUCA

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.