Visualizzazione dei risultati da 1 a 8 su 8
  1. #1
    Utente di HTML.it
    Registrato dal
    Sep 2009
    Messaggi
    5

    Problema realizzazione blog jsp-servlet

    Salve,
    in primis complimenti per la community di supporto. Veniamo al dunque:
    Per esercitarmi ho deciso di realizzare un blog utilizzando servlet e pagine JSP. Ecco i sorgenti della jsp per inserire dei post e la relativa servlet di comunicazione al DB.
    codice:
    <%@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>
            <link rel="stylesheet" type="text/css" href="form.css"/>
        </head>
        <body>
            <h2 align="center">Login</h2>
    <form id="form1" name="form1" method="post" action="chiamaServlet">
    
      <label><div class="username">Username</div>
      <div class="input"><input name="username" type="text" id="username" maxlength="50" /></div>
      <div class="break"></div>
      </label>
      <label><div class="username">Password</div>
      <div class="input"><input name="password" type="password" id="password" maxlength="50" /></div>
      </label>
      <div class="break"></div>
    <p align="center">
      <input class="invia" type="submit" name="button" id="button" value="Invia" />
    
    </form>
        </body>
    </html>
    codice:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package blog;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    /*import java.util.*;*/
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.text.*;
    import java.sql.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    
    /**
     *
     * @author Francesco
     */
    public class inserisciCommento extends HttpServlet {
        private DataAccess connection;
        
        @Override
        public void init() throws ServletException {
        super.init();
        connection=DataAccess.newDataAccess();
        }
    
    
    
    
    
        /** 
         * 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, SQLException, ParseException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                //ricevo i dati in input e li immagazzino in stringhe
                String autore = request.getParameter("autore");
                String titolo = request.getParameter("titolo");
                String articolo = request.getParameter("articolo");
    
                       
                GregorianCalendar gc= new GregorianCalendar();
                Date d =  (Date) gc.getTime();
                SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
                String data= sdf.format(d);
                out.println(data);
                Calendar ctoDay = Calendar.getInstance();
                java.sql.Date oggi = new java.sql.Date((ctoDay.getTime()).getTime()); // data odierna.
               
                   
    
                PreparedStatement pst = null;
                pst = connection.prepareStatement("INSERT INTO articoli  (art_autore,art_titolo,art_articolo,art_data) VALUES ((?),(?),(?),(?))");
                pst.setString(1, autore);
                pst.setString(2,titolo);
                pst.setString(3,articolo);
                pst.setDate(4,oggi);
                pst.executeUpdate();
                pst.close();
                                
                
                /* TODO output your page here
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet inserisciCommento</title>");  
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet inserisciCommento at " + request.getContextPath () + "</h1>");
                out.println("</body>");
                out.println("</html>");
                */
            } 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 {
            try {
                try {
                    processRequest(request, response);
                } catch (ParseException ex) {
                    Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (SQLException ex) {
                Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
    
        /** 
         * 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 {
            try {
                try {
                    processRequest(request, response);
                } catch (ParseException ex) {
                    Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (SQLException ex) {
                Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
        /** 
         * Returns a short description of the servlet.
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    
    }
    Ed ecco la servlet che si occupa della connessione al DB

    codice:
    package blog;
    
        
    
        import com.mysql.jdbc.Connection;
        import java.sql.*;
        import javax.servlet.ServletException;
    
        /**
        *
        * @author katone
        */
    
        public class DataAccess {
    
        //Creazione singleton
        private static DataAccess connessione = null;
    
        public synchronized static DataAccess newDataAccess() throws ServletException {
        if (connessione == null) connessione = new DataAccess();
        return connessione;
        }
        private Connection c = null;
    
        public ResultSet GenericQuery(String _sql){
            Statement s = null;
            ResultSet r;
            try{
            s = (Statement) c.createStatement();
            r = s.executeQuery(_sql);
            return r;
            }
            catch (SQLException e) {
            e.printStackTrace();
            return null;
            }
        }
    
        //costruttore privato della classe DataAccess
        private DataAccess() throws ServletException {
        try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = ("jdbc:mysql://localhost/blog");
        String user = ("root");
        String pass = ("francesco");
        c = (Connection) DriverManager.getConnection(url, user, pass);
        }catch(ClassNotFoundException e) {
        e.printStackTrace();
        throw new ServletException("Errore di caricamento driver database",e);
        } catch(SQLException e) {
        e.printStackTrace();
        throw new ServletException("Errore di connessione al database",e);
        }
        }
    
        //Chiusura della connesione col db
        @Override
        protected void finalize() throws Throwable {
        super.finalize();
        if (c!=null) c.close();
        }
    
        PreparedStatement prepareStatement(String string) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        }


    Purtroppo, non avviene alcuna insert all'interno del DB in questione.
    Vi ringrazio anticipatamente per gli eventuali aiuti e/o suggerimenti.

  2. #2
    a occhio direi che nella form della pahina jsp la action chiama una servlet inesistente. Cioe'
    Codice PHP:
    <form id="form1" name="form1" method="post" action="chiamaServlet"
    la 'chiamaServlet' non esiste. Rivedi il codice e posta l'errore che si capisce meglio in base ai log!

  3. #3
    Utente di HTML.it
    Registrato dal
    Sep 2009
    Messaggi
    5
    Intanto grazie della collaborazione. mea culpa.. ho postato il form errato.. ad ogni modo il form di inserimento post punta alla servlet in questione ovvero inserisciCommento. Ecco il log
    codice:
    GRAVE: Servlet.service() for servlet inserisciCommento threw exception
    java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
            at blog.inserisciCommento.processRequest(inserisciCommento.java:58)
            at blog.inserisciCommento.doPost(inserisciCommento.java:126)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
            at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
            at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
            at java.lang.Thread.run(Thread.java:619)
    Come pensavo l'errore sta sicuramente nella creazione della data. Sto cercando di imparare esercitandomi il più possibile ma ovviamente, cercando di spingermi oltre, vengono a mancare determinate conoscenze.

  4. #4
    Utente di HTML.it
    Registrato dal
    Sep 2009
    Messaggi
    5

    Non ci siamo

    Ecco il codice ripulito e e corretto
    Codice PHP:
    protected void processRequest(HttpServletRequest requestHttpServletResponse response)
        
    throws ServletExceptionIOExceptionSQLExceptionParseException {
            
    response.setContentType("text/html;charset=UTF-8");
            
    PrintWriter out response.getWriter();
            
    Connection con null;
            
    String sql null;
            
    PreparedStatement inserisciCommento null;
            try {                 
                    Class.
    forName("com.mysql.jdbc.Driver");
            }
             catch(
    java.lang.ClassNotFoundException ex){
                    
    System.err.print(ex);
             }


            try{

                
    String autore request.getParameter("autore");
                
    String titolo request.getParameter("titolo");
                
    String articolo request.getParameter("articolo");
                
    String url = ("jdbc:ysql://localhost/blog");
                
    String usr "root";
                
    String pwd "francesco";
                
    con DriverManager.getConnection(urlusrpwd);
                
    sql = ("INSERT INTO articoli  (art_autore,art_titolo,art_articolo,) VALUES ((?),(?),(?))");
                
    inserisciCommento con.prepareStatement(sql);
                
    inserisciCommento.setString(1,autore);
                
    inserisciCommento.setString(2,titolo);
                
    inserisciCommento.setString(3,articolo);
                
    int inserimento inserisciCommento.executeUpdate();
                if(
    inserimento == 1){
                    
    out.println("Inserimento Effettuato");
                }
                else{
                    
    out.println("Inserimento Non Effettuato");
                }
                }
            catch(
    SQLException sqlexx){
                
    System.err.println(sqlexx.getMessage());
            }
                
                
    /* TODO output your page here
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet inserisciCommento</title>");  
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet inserisciCommento at " + request.getContextPath () + "</h1>");
                out.println("</body>");
                out.println("</html>");
                */
             
    finally {
                 try{
                     if(
    inserisciCommento!= null){
                         
    inserisciCommento.close();
                     }
                     if(
    con!=null){

                         
    con.close();
                     }

                 }
                 catch(
    SQLException sqlexxx){
                     
    System.err.print(sqlexxx.getMessage());
                 }
                
    out.close();
            } 
    Niente da fare. Non funge.. suggerimenti?

  5. #5
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    7
    Ciao, credo che ci siano, semplicemente errori di scrittura
    String url = ("jdbc:ysql://localhost/blog"); <-- qui manca la lettera m .....

    String url = ("jdbc:mysql://localhost/blog"); deve essere cosi..

    sql = ("INSERT INTO articoli (art_autore,art_titolo,art_articolo,) VALUES ((?),(?),(?))"); <-- qui ce una virgola finale che non va , poi non racchiudere una stringa tra parentesi ....

    sql = "INSERT INTO articoli (art_autore,art_titolo,art_articolo) VALUES (?,?,?)"; <-- va cosi..


    nella servlet invoca il metodo solo nel doPost, dato che il form chiama il metod=post..

    funziona benissimo cosi... ciao

  6. #6
    Utente di HTML.it
    Registrato dal
    Sep 2009
    Messaggi
    5
    Grazie per la collaborazione! Corretti errori di scrittura.. Ho invocato il metodo processRequest(request, response) nel doPost().

    codice:
    @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            try {
                processRequest(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(inserisciCommento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    Ma viene segnalato un errore riguardo l'esecuzione della query d'inserimento dati. Ecco il log
    codice:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES ('ciccio','mario','pippo')' at line 1
    Risulta un apice in più quando la String sql recita
    codice:
    sql = "INSERT INTO articoli(art_autore,art_titolo,art_articolo,) VALUES (?,?,?)";

  7. #7
    Utente di HTML.it
    Registrato dal
    Sep 2009
    Messaggi
    5
    Trovato c'è una virgola in più

  8. #8
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    7
    grande

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.