Salvare nome, cognome e mail in db mysql

di il
4 risposte

Salvare nome, cognome e mail in db mysql

Salve ragazzi,

spero di postare nella sezione giusta, sto cercando di creare a scopo didattico un Dinamic Web Project che salvi su un DB mysql il nome, il cognome e la mail dell'utente.

Ho creato due classi java


package modello;

// javaBean per memorizzare i dati di un ospit nel guestbook

public class GuestBean {
	
	private String firstName, lastName, email;

	   // imposta il nome dell'ospite
	   public void setFirstName( String name ) {
	      firstName = name;  
	   }
	   
	   // ottiene il nome dell'ospite
	   public String getFirstName() {
	      return firstName;  
	   }

	   // imposta il cognome dell'ospite
	   public void setLastName( String name ) {
	      lastName = name;  
	   }

	   // ottiene il cognome dell'ospite
	   public String getLastName() {
	      return lastName;  
	   }

	   // imposta l'indirizzo email dell'ospite
	   public void setEmail( String address ) {
	      email = address;
	   }

	   // ottieni l'indirizzo email dell'ospite
	   public String getEmail() {
	      return email;  
	 
	}

}



package modello;

import java.io.*;
import java.sql.*;
import java.util.*;

public class GuestDataBean {
	
	private Connection connection;
	   private Statement statement;
	   
	   // construct TitlesBean object 
	   public GuestDataBean() throws Exception {
	        
	         Class.forName("com.mysql.jdbc.Driver");

	         // connect to the database
	         connection = DriverManager.getConnection(
	            "jdbc:mysql://localhost:/GuestBean?user=root&password=password" );

	         statement = connection.createStatement();
	   }

	   // return an ArrayList of GuestBeans
	   public List getGuestList() throws SQLException {
	      List guestList = new ArrayList();

	      // obtain list of titles
	      ResultSet results = statement.executeQuery( 
	         "SELECT firstName, lastName, email FROM guests" );

	      // get row data
	      while ( results.next() ) {
	         GuestBean guest = new GuestBean();

	         guest.setFirstName( results.getString( 1 ) );
	         guest.setLastName( results.getString( 2 ) );
	         guest.setEmail( results.getString( 3 ) );

	         guestList.add( guest ); 
	      }         

	      return guestList; 
	   }
	   
	   // insert a guest in guestbook database
	   public void addGuest( GuestBean guest ) throws SQLException {
	      statement.executeUpdate( "INSERT INTO guests ( firstName, " + 
	         "lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" + 
	         guest.getLastName() + "', '" + guest.getEmail() + "' )" );
	   }

	   // close statements and terminate database connection
	   protected void finalize()
	   {
	      // attempt to close database connection
	      try {
	         statement.close();
	         connection.close();
	      }

	      // process SQLException on close operation
	      catch ( SQLException sqlException ) {
	         sqlException.printStackTrace();
	      }
	   }
}
e 3 jsp in questo modo

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- guestBookErrorPage.jsp -->

<%-- page settings --%>
<%@ page isErrorPage = "true" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>

<html xmlns = "http://www.w3.org/1999/xhtml">

   <head>
      <title>Error!</title>

      <style type = "text/css">
         .bigRed {
            font-size: 2em;
            color: red; 
            font-weight: bold;
         }
      </style>
   </head>

   <body>
      <p class = "bigRed"> 

      <% // scriptlet per determinare il tipo di eccezione
         // e stampare l'inizio del messaggio di errore
         if ( exception instanceof SQLException )
      %>

            An SQLException
			
      
      <%
		  else if ( exception instanceof ClassNotFoundException )
      %>

            A ClassNotFoundException
      
      <%
         else
      %>

            An exception

      <%-- fine scriptlett per inserire dati fissi --%>

         <%-- continua output messaggio di errore --%>
         occurred while interacting with the guestbook database. 
      </p>

      <p class = "bigRed">
         The error message was:<br />
         <%= exception.getMessage() %>
      </p>

      <p class = "bigRed">Please try again later</p>
   </body>

</html>

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- guestBookLogin.jsp -->

<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>

<%-- beans used in this JSP --%>
<jsp:useBean id = "guest" scope = "page" 
   class ="modello.GuestBean" />
<jsp:useBean id = "guestData" scope = "request" 
   class = "modello.GuestDataBean" />

<html xmlns = "http://www.w3.org/1999/xhtml">

<head>
   <title>Guest Book Login</title>

   <style type = "text/css">
      body { 
         font-family: tahoma, helvetica, arial, sans-serif;
      }

      table, tr, td { 
         font-size: .9em;
         border: 3px groove;
         padding: 5px;
         background-color: #dddddd;
      }
   </style>
</head>

<body>
   <jsp:setProperty name = "guest" property = "*" />

   <% // start scriptlet

      if ( guest.getFirstName() == null || 
           guest.getLastName() == null ||
           guest.getEmail() == null ) {

   %> <%-- fine scriptlett per inserire i dati fissi--%>

         <form method = "post" action = "guestBookLogin.jsp">
            <p>Enter your first name, last name and email
               address to register in our guest book.</p>

            <table>
               <tr>
                  <td>First name</td>

                  <td>
                     <input type = "text" name = "firstName" />
                  </td>
               </tr>

               <tr>
                  <td>Last name</td>

                  <td>
                     <input type = "text" name = "lastName" />
                  </td>
               </tr>

               <tr>
                  <td>Email</td>

                  <td>
                     <input type = "text" name = "email" />
                  </td>
               </tr>

               <tr>
                  <td colspan = "2">
                     <input type = "submit" 
                        value = "Submit" />
                  </td>
               </tr>
            </table>
         </form>

   <% // continua scriptlet

      }  // end if
      else {
         guestData.addGuest( guest );

   %> <%-- end scriptlet to insert jsp:forward action --%>

         <%-- forward to display guest book contents --%>
         <jsp:forward page = "guestBookView.jsp" />

   <% // continuea scriptlet

      }  // fine else

   %> <%-- end scriptlet --%>
</body>

</html>

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 25.23: guestBookView.jsp -->

<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import = "modello.*" %>

<%-- GuestDataBean per ottenere la lista degli ospiti --%>
<jsp:useBean id = "guestData" scope = "request" 
   class = "modello.GuestDataBean" />

<html xmlns = "http://www.w3.org/1999/xhtml">

   <head>
      <title>Guest List</title>

      <style type = "text/css">
         body { 
            font-family: tahoma, helvetica, arial, sans-serif; 
         }

         table, tr, td, th { 
            text-align: center;
            font-size: .9em;
            border: 3px groove;
            padding: 5px;
            background-color: #dddddd;
         }
      </style>
   </head>

   <body>
      <p style = "font-size: 2em;">Guest List</p>

      <table>
         <thead>
            <tr>
               <th style = "width: 100px;">Last name</th>
               <th style = "width: 100px;">First name</th>
               <th style = "width: 200px;">Email</th>
            </tr>
         </thead>

         <tbody>

         <% // inizio scriptlet

            List guestList = guestData.getGuestList();
            Iterator guestListIterator = guestList.iterator();
            GuestBean guest;

            while ( guestListIterator.hasNext() ) {
               guest = ( GuestBean ) guestListIterator.next();

         %> <%-- fine scriptlet; inserisci dati fissi --%>
 
               <tr>
                  <td><%= guest.getLastName() %></td>

                  <td><%= guest.getFirstName() %></td>

                  <td>
                     <a href = "mailto:<%= guest.getEmail() %>">
                        <%= guest.getEmail() %></a>
                  </td>
               </tr>

         <% // continua scriptlet

            } // fine while

         %> <%-- end scriptlet --%>
         
         </tbody>
      </table>
   </body>

</html>
nel file web.xml ho inserito

<welcome-file>guestBookLogin.jsp</welcome-file>

e il mio db l'ho creato in questo modo

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

-- Dump della struttura del database dizionario
CREATE DATABASE IF NOT EXISTS `GuestBean` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `GuestBean`;

create table guests (
	firstName varchar (20) NOT NULL ,
   lastName varchar (20) NOT NULL ,
	email varchar (50) NOT NULL PRIMARY KEY
) 
;
ed infine ho importato il jar

mysql-connector-java-5.x.xxx-bin.jar.

quando faccio partire il mio progetto mi esce sempre questo errore:

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 38 in the jsp file: /guestBookErrorPage.jsp
Syntax error on token "else", delete this token
35: 			
36:       
37:       <%
38: 		  else if ( exception instanceof ClassNotFoundException )
39:       %>
40: 
41:             A ClassNotFoundException


An error occurred at line: 44 in the jsp file: /guestBookErrorPage.jsp
Syntax error on token "else", delete this token
41:             A ClassNotFoundException
42:       
43:       <%
44:          else
45:       %>
46: 
47:             An exception


Stacktrace:
	org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
	org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
	org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:485)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:379)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
	org.apache.jasper.compiler.Compiler.compile(Compiler.java:341)
	org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:662)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
	org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
	org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:872)
	org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
	org.apache.jsp.guestBookLogin_jsp._jspService(guestBookLogin_jsp.java:224)
	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
credo, anche se non ne sono sicuro, che dipendi dal jar e che non riesca a trovare Class.forName("com.mysql.jdbc.Driver") anche se io il jar l'ho importato correttamente.

Sapete come posso fare per risolvere?

4 Risposte

  • Re: Salvare nome, cognome e mail in db mysql

    Lo hai messo anche nella directory lib della web application?
    In alternativa mettilo nella directory GENERALE lib di tomcat

    Nota: il titolo non centra una cicca con il tuo problema!!!!
    Il tuo problema e': non trova la classe driver JDBC per MySQL!
  • Re: Salvare nome, cognome e mail in db mysql

    migliorabile ha scritto:


    Lo hai messo anche nella directory lib della web application?
    In alternativa mettilo nella directory GENERALE lib di tomcat
    si messo anche sia nella directory lib della web application che in lib di tomcat ma mi da lo stesso errore.

    migliorabile ha scritto:


    Nota: il titolo non centra una cicca con il tuo problema!!!!
    Il tuo problema e': non trova la classe driver JDBC per MySQL!
    si lo so, ma siccome non ero sicuro che fosse quello il problema ho pensato di intitolare la 3D con quello che voglio fare, così magari qualcuno può anche darmi dei suggerimenti su come farlo nel modo più corretto.

    Ma se è un problema cambio subito il titolo
  • Re: Salvare nome, cognome e mail in db mysql

    Altra cosa: hai chiamato:
    
    Class.fromName("com.mysql.jdbc.Driver")
    
    ?
    Altra alternativa: usa il connection-pool di Tomcat: devi definire il data source

    In generale non e' una buona idea che OGNI webapp gestisca per conto suo le connessioni al DB.
    E meglio avere una gestione centralizzata.
  • Re: Salvare nome, cognome e mail in db mysql

    Risolto, funziona tutto perfettamente.

    Ora sto cercando di inserire la modifica e la cancellazione degli utenti.
Devi accedere o registrarti per scrivere nel forum
4 risposte