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>Ed ecco la servlet che si occupa della connessione al DBcodice:/* * 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> }
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.

Rispondi quotando
Grazie per la collaborazione! Corretti errori di scrittura.. Ho invocato il metodo processRequest(request, response) nel doPost().
