Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 14
  1. #1

    [Servlet]Creare una web page con un BufferedWriter

    ciao a tutti
    vorrei creare all'interno di una mia servlet un file .htm
    io ho provato a mettere il codice in questo modo ma mi da il seguente errore
    codice:
    /**
     * @(#)AddItems.java
     *
     *
     * @author Raffaella
     * @version 1.00 2007/5/30
     */
    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;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    
    public class AddItems {
    
        Document documento = null;
    	Element elementoItems = null;
    	String id, author, description;	
    	
    	public void aggiungiItem(){
    		Element added = new Element("item");
    		Element element_id = new Element("id");
    		Element element_author = new Element("author");
    		Element element_description = new Element("description");
    		
    		element_id.setText(id);
    		element_author.setText(author);
    		element_description.setText(description);
    		
    		added.addContent(element_id);
    		added.addContent(element_author);
    		added.addContent(element_description);
    			
    		elementoItems.addContent(added);
    	}
    	
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		
    		StringBuffer buf = new StringBuffer();
    		response.setContentType("text/html");
    		PrintWriter responseOutput = response.getWriter();
    		buf.append("<html><head></head><body><table border=\"1\" width=\"40%\" align=\"center\"><tbody><tr>");
    		String controllo = new String("ok");
    		//RECUPERO LE INFORMAZIONI INVIATE DAL FORM
    		id = request.getParameter("id");
    		author = request.getParameter("author");
    		description = request.getParameter("description");
    		
    		if ((id != "") && (author != "") && (description != "")){		
    
    
    
    			//creiamo un oggetto FileWriter per poter creare una pagina web inserendo in un combobox
    			//gli id degli item aggiunti	
    			try {
    				//se il file non esiste lo crea e provvede a inserirvi l'elemento
    				BufferedWriter webPage = new BufferedWriter( new FileWriter("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/ChooseItem.htm"));
    				String text1 = "<html><head><title>Choose Item</title></head><body><h2>Choose An Item</h2><FORM id=\"form_item_chose\" METHOD=\"post\" ACTION=\"ChooseItem\"><b ID=\"ItemChose\">Choose an item to rate to a customer.
    Choose one of these
    <SELECT NAME=\"chose\"><OPTION>";
    				String text2 = "</OPTION></SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>";
    				webPage.write(text1 + id + text2);
    			}
    			catch (IOException ex) {
    				System.err.println(ex);
    			}[/b]
    
    
    			//CONTROLLO SE ESISTE GIA' UN FILE .XML CHE SI CHIAMA REGISTRATED
    			String path = new String ("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/xml/Item.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();
    				elementoItems = new Element("itemAdded");
    				//AGGIUNGO IL REGISTARTO CHE RISULTA IL PRIMO DATO CHE IL FILE REGISTRATI.XML NON ESISTEVA
    				aggiungiItem();
    				//SCRIVO IL DOCUMENT NEL FILE		
    				documento = new Document(elementoItems);
    				XMLOutputter xmlOutputter = new XMLOutputter();
    				try{
       					FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); 
       					xmlOutputter.output(documento, fileOutputStream);
    					buf.append("<td align=\"center\">Item, " + id + " added.
    
    <a href=\"AddItem.htm\">Go Back</a></p>
    
    <a href=\"Recommendations.htm\">Proceed</a></p></td>");
     				}
    	 			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 DICO DI CAMBIARE LOGIN
    				elementoItems = documento.getRootElement(); 
    				List lista_items = elementoItems.getChildren();
    				// ottengo un iteratore alla lista chiamando il metodo iterator() di Collection (essendo una list una collection) 
     				Iterator iteratore = lista_items.iterator();
    				while (iteratore.hasNext())
    	 			{ 
    	   				// ottengo l'elemento corrente chiamando next() sull'iteratore 
    	   				Element id_corrente = (Element)iteratore.next(); 
    					if (id.equals(id_corrente)){
    						buf.append("<td align=\"center\">Item Already Added.
    
    <a href=\"AddItem.htm\">Go Back</a></p></td>");
    						controllo = new String("ko");
    						break;
    					}
    	 			}
    				if (controllo.equals("ok")){
    					//RISCRIVO L'INTERO DOCUMENTO NEL FILE XML DOPO AVER AGGIUNTO IL REGISTRATO
    					aggiungiItem();
    					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 lo accetta
    					//xmlOutputter.setFormat(Format.getPrettyFormat());
    	    			try{
    	   					FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); 
    	   					xmlOutputter.output(documento, fileOutputStream);
    						buf.append("<td align=\"center\">Item Successfull Added.
    
    <a href=\"AddItem.htm\">Go Back</a></p>
    
    <a href=\"Recommendations.htm\">Proceed</a></p></td>");
    	 				}
    			 		catch (FileNotFoundException ex){
    	   					System.err.println(ex);
    	 				}
    			 		catch (IOException ex){
    	   					System.err.println(ex);
    	 				}
    				}			
    			}
    		}
    		else{
    			buf.append("<td align=\"center\">Missing informations, fields with * are compulsory.</td></p><a href=\"AdminRegistration.htm\">Go Back</a></td>");
    		}
    		buf.append("</tr></tbody></table></body></html>");
    		responseOutput.println(buf.toString());
    		responseOutput.close();
        }
        
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            doPost(request, response);
        }
    }
    codice:
    HTTP Status 500 - 
    
    --------------------------------------------------------------------------------
    
    type Exception report
    
    message 
    
    description The server encountered an internal error () that prevented it from fulfilling this request.
    
    exception 
    
    javax.servlet.ServletException: Error allocating a servlet instance
    	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
    	org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
    	org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
    	org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
    	java.lang.Thread.run(Unknown Source)
    
    
    root cause 
    
    java.lang.NoClassDefFoundError: projectservlet/AddItems (wrong name: AddItems)
    	java.lang.ClassLoader.defineClass1(Native Method)
    	java.lang.ClassLoader.defineClass(Unknown Source)
    	java.security.SecureClassLoader.defineClass(Unknown Source)
    	org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1817)
    	org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:872)
    	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1325)
    	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
    	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
    	org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
    	org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
    	org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
    	java.lang.Thread.run(Unknown Source)
    
    
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs.
    
    
    --------------------------------------------------------------------------------
    
    Apache Tomcat/6.0.13
    perkè cosa ho sbagliato??
    e poi è possibile leggere con un BufferedReader una parola e sostituirla con un altra una volta ke è stata trovata all'interno della linea appena letta?io ho visto nella doc della sun ma non ho trovato nessun metodo ke sia equivalente a find() o replace()
    non so la cosa è fattibile?
    grazie mille

  2. #2
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    Per l'eccezione, non trova la classe. Possibile causa: hai mappato la servlet come facente parte di un package, ma manca la dichiarazione package all'inizio del codice della servlet (almeno nel codice che hai postato tu).
    Per la seconda domanda, il metodo readLine() restituisce la riga letta sotto forma di String. La classe String ha il metodo replaceAll() e replaceFirst() per rimpiazzare delle stringhe(indicabili anche attraverso un espressione regolare) con altre stringhe. Vedi documentazione della classe String.

  3. #3
    uhm hai ragione tu
    evidentemente nel copiare ho cancellato anke nel file .java il package ke avevo inserito cmq provo come hai detto tu ora vedo per la classe string
    grazie ancora

  4. #4
    ah un altra cosa.. è possibile verificare ke quel file ke ho crato con il bufferedWriter esista o meno?
    o provato a mettere sempre exists() però non me lo riconosce me lo da come errore

  5. #5
    ho risolto con l'exist() il problema ke con questo pezzo di codice mi fa ciò ke deve fare solo ke se inserisco un altro elemento anzikè sostituirmi un pezzo di codice con un altro nella pagina web mi cancella tutto
    cosa ho sbagliato?
    vorrei cercare di prendere una sottostringa e di sostituirla con un'altra e di continuare a scrivere nello stesso file .htm
    codice:
    //creamo un oggetto FileWriter per poter creare una pagina web inserendo in un combobox
    			//gli id degli item aggiunti	
    			try {
    				//creamo un oggetto File per creare un file .htm sul disco
    				String webPath = new String ("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/ChooseItem.htm");
    				File TempWebPage = new File (webPath);
    				//verifica se il file esiste o meno
    				if (!TempWebPage.exists()){
    					//se il file non esiste lo crea
    					TempWebPage.createNewFile();
    					//se il file non esiste provvede a inserirvi gli elementi
    					BufferedWriter webPage = new BufferedWriter( new FileWriter("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/ChooseItem.htm"));
    					String text1 = "<html><head><title>Choose Item</title></head><body><h2>Choose An Item</h2><FORM id=\"form_item_chose\" METHOD=\"post\" ACTION=\"ChooseItem\"><b ID=\"ItemChose\">Choose an item to rate to a customer.[/b]
    Choose one of these
    <SELECT NAME=\"chose\"><OPTION>";
    					String text2 = "</OPTION></SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>";
    					webPage.write(text1 + id + text2);
    					webPage.close();
    				}
    				else{
    					//se il file esiste provvede ad aggiungere altri elementi
    					BufferedReader readWebPage = new BufferedReader( new FileReader("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/ChooseItem.htm"));
    					String line;
    					while ((line = readWebPage.readLine()) != null){
    						if (line.endsWith("</SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>"));
    						BufferedWriter webPage = new BufferedWriter( new FileWriter("C:/Programmi/Apache Software Foundation/Tomcat 6.0/webapps/ITemRecommender/ChooseItem.htm"));
    						String text3 = "";
    						webPage.write(line.replaceAll("</SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>", "<OPTION>" + id + "</OPTION></SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>"));
    						webPage.close();
    					}
    					readWebPage.close();
    				}
    			}
    			catch (IOException ex) {
    				System.err.println(ex);
    			}
    /*			catch (FileNotFoundException ex) {
    				System.err.println(ex);
    			}*/
    la parte else dell'if di exists non va come dovrebbe andare.. cosa ho sbagliato?

  6. #6
    Utente di HTML.it
    Registrato dal
    Mar 2007
    Messaggi
    230
    Prova così:

    File TempWebpage = new File(webPath);

    //Crea il file se non esiste

    boolean success = TempWebPage.createNewFile();

    if (success) {

    // Il file non esisteva ed è stato creato

    } else {

    // Il file è già esistente

    }

    } catch (IOException e) {

    }

  7. #7
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    Inizializzando un BufferWriter all'interno del while, ad ogni iterazione ne apri uno nuovo senza chiudere il precedente e quello nuovo credo riparta da capo. Per far meno confusione, credo che ti convenga aprire lo stream in lettura, leggere tutto l'html e salvarlo in una Stringa, fare il replaceAll (o anche solo replace visto che non usi espressioni regolari) su questa stringa, aprire lo stream in scrittura e fare la write della stringa che ti sovrascrive il vecchio contenuto.
    codice:
    String webPath = new String("C:/Documents and Settings/Simone/Desktop/ChooseItem.htm");
    File TempWebPage = new File(webPath);
    //verifica se il file esiste o meno
    if (!TempWebPage.exists()){
       //se il file non esiste lo crea
       TempWebPage.createNewFile();
       //se il file non esiste provvede a inserirvi gli elementi
       BufferedWriter webPage = new BufferedWriter( new FileWriter(TempWebPage));
       String text1 = "<html><head><title>Choose Item</title></head><body><h2>Choose An Item</h2><FORM id=\"form_item_chose\" METHOD=\"post\" ACTION=\"ChooseItem\"><b ID=\"ItemChose\">Choose an item to rate to a customer.[/b]
    Choose one of these
    <SELECT NAME=\"chose\"><OPTION>";
       String text2 = "</OPTION></SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>";
       webPage.write(text1 + id + text2);
       webPage.close();
    } else{
       BufferedReader readWebPage = new BufferedReader( new FileReader(TempWebPage));
       String line;
       String tmp = "";
       //Leggo tutto il file e lo butto in una variabile temporanea
       while ((line = readWebPage.readLine()) != null){
          tmp += line;
       }
       readWebPage.close();
       //Faccio il mio bel replace (o replaceAll, come preferisci)
       tmp = tmp.replace("</SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>", "<OPTION>" + id + "</OPTION></SELECT></p>
    
    
    <INPUT id = \"send\" TYPE=\"submit\" VALUE=\"Send\" /></p>
    </FORM></body></html>");
       //Apro lo stream in scrittura e sovrascrivo il file
       BufferedWriter webPage = new BufferedWriter( new FileWriter(TempWebPage));
       webPage.write(tmp);
       webPage.close();
    }
    Una curiosita': come mai vuoi salvare dinamicamente le pagine html?

  8. #8
    grazie l'avevo pensato anke io di fare così
    faccio questo perkè la pagina ke mi crea sarà oggetto di un'altra servlet per fare il recommender degli item ad un utente ecco perkè
    in pratica scelgo gli item a cui voglio far dare un rate dall'utente e un'altra servlet mi deve creare per quel utente un'altro file xml contenente tutti gli item ke lui ha votato con il relativo rate

  9. #9
    Utente di HTML.it
    Registrato dal
    Apr 2007
    Messaggi
    906
    Beh, forse sarebbe meglio salvare la stringa html in session. Non so se e' il tuo caso, ma attenta agli accessi concorrenti; se due utenti accedono alla pagina, il secondo utente sovrascrive il file del primo. Ciao

  10. #10
    uhm grazie per l'avvertimento
    ma in che sento.. salvare la stringa html in session? cioè?
    grazie mille di tutto

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.