Salve a tutti ragazzi, innanzitutto spero di stare postando nella sezione adatta, se così non fosse mi scuso anticipatamente.
Ho un problema a cui non riesco a venire a capo, ho creato un Dinamic Web Project con Eclipse che mi permette di inserire nome, cognome e mail di un utente e una volta inserito correttamente in un db e visualizzato in una tabella con tutti gli utenti. ora vorrei implementare anche la modifica e la cancellazione dei record.
Ho creato due classi java
codice:
package modello;
public class GuestBean {
private String firstName, lastName, email;
public void setFirstName( String name ) {
firstName = name;
}
public String getFirstName() {
return firstName;
}
public void setLastName( String name ) {
lastName = name;
}
public String getLastName() {
return lastName;
}
public void setEmail( String address ) {
email = address;
}
public String getEmail() {
return email;
}
}
codice:
package modello;
import java.sql.*;
import java.util.*;
public class GuestDataBean {
private Connection c;
private Statement s;
public GuestDataBean() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
// connessiona al DB
c = DriverManager.getConnection("jdbc:mysql://localhost/guestbean?user=root&password=psw" );
s = c.createStatement();
}
// ritorna lista ospiti
public List getGuestList() throws SQLException {
List guestList = new ArrayList();
// ottiene lista di ospiti
ResultSet results = s.executeQuery(
"SELECT firstName, lastName, email FROM guests" );
// ottinene dati dalle righe
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;
}
// inserisce un ospite nel db
public void addGuest( GuestBean guest ) throws SQLException {
s.executeUpdate( "INSERT INTO guests ( firstName, " +
"lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" +
guest.getLastName() + "', '" + guest.getEmail() + "' )" );
}
// rimuovi un ospite nel db
public int removeGuest(GuestBean guest) throws SQLException {
String email = guest.getEmail();
Statement st = c.createStatement();
String sql = "DELETE FROM guests WHERE = '"+email+"'";
int result = st.executeUpdate(sql);
st.close();
return result;
}
//modifica un opsite del db
public int updateGuest(GuestBean guest, String mail) throws SQLException {
String lastName= guest.getLastName();
String firstName = guest.getFirstName();
String email = guest.getEmail();
Statement st = c.createStatement();
String sql = "UPDATE guests SET email = '"+email+"', lastName = '"+lastName+"', fistName ='"+firstName+"' WHERE mail = '"+mail+"'";
int result = st.executeUpdate(sql);
st.close();
return result;
}
// trova ospite
public GuestBean trovaOspite(String email) throws SQLException {
GuestBean g = null;
Statement st = c.createStatement();
// troviamo il record con isbn assegnato
ResultSet rs = st.executeQuery("SELECT * FROM guest WHERE email ='"+email+"'");
// se esiste il record
if (rs.next()) {
String Email = rs.getString("email");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
// restituiamo l'autore con idAutore assegnato
// istanziamo un libro con isbn, titolo e autore
g= new GuestBean(Email,firstName,lastName);
}
rs.close();
st.close();
return g;
}
// chiude istruzioni e termina la connessione col db
protected void finalize()
{
// tenta di chiudere la connessione col db
try {
s.close();
c.close();
}
// gestisce SQLException nelle operazioni di chiusura
catch ( SQLException sqlException ) {
sqlException.printStackTrace();
}
}
// chiusura della connessione
public void closeConn() throws SQLException {
c.close();
}
// caricamento dei driver e apertura della connessione al database
public void openConn() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// connessiona al DB
c = DriverManager.getConnection("jdbc:mysql://localhost/guestbean?user=root&password=psw" );
} // fine metodo open()
}
JSP
codice:
<?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>
codice:
?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 usati in questo 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
%> <%-- 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" required/>
</td>
</tr>
<tr>
<td>Last name</td>
<td>
<input type = "text" name = "lastName" required />
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type = "text" name = "email" required/>
</td>
<tr>
<td colspan = "2">
<input type = "submit" value = "Aggiungi" />
<a href ="guestBookView.jsp">Visualizza tutti gli iscritti</a>
</td>
</tr>
</table>
</form>
<% // continua scriptlet
// if
if ( guest.getFirstName() != null &&
guest.getLastName() != null &&
guest.getEmail() != null ) {
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>
codice:
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- 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>
<th style = "width: 100px;">Seleziona per modificare</th>
<th style = "width: 100px;">Seleziona per cancellare</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 --%>
<form>
<tr>
<td><%= guest.getLastName() %></td>
<td><%= guest.getFirstName() %></td>
<td>
<a href = "mailto:<%= guest.getEmail() %>">
<%= guest.getEmail() %></a>
</td>
<td>
<a href ='modifica.jsp?email="+guest.getEmail()+"'>Modifica</a>
</td>
<td>
<a href="cancella.jsp?Email=guest.getEmail()">Cancella</a>
</td>
</tr>
<% // continua scriptlet
// fine while
}
%> <%-- end scriptlet --%>
</form>
</tbody>
</table>
</body>
codice:
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page errorPage = "gestBookErrorPage.jsp" %>
<%@page import = "modello.GuestBean" %>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cancellazione</title>
<style type="text/css">
body,td,th {
font-family: Verdana;
font-size: 16px;
border: 0px;
}
</style>
</head>
<body>
<%
// se l'utente ha cliccato sul link "Cancella"
if (request.getParameter("mail") != null) {
%>
<jsp:useBean id = "guestData" class = "modello.GuestDataBean"/>
<%
// aprimo la connessione
guestData.openConn();
// recuperiamo la mail del guest da cancellare
String email = request.getParameter("email");
// carichiamo in memoria il guest
GuestBean g = guestData.trovaOspite(email);
// cancelliamo il guest
if(g != null) {
int result = guestData.removeGuest(g);
//qui vorrei inserire un messaggio di ok
}else{
//qui vorrei inserire un messaggio di errore
}
guestData.closeConn();
}
%>
</body>
</html>
Sto cercand di implementare la cancellazione, qualcuno saprebbe darmi una mano?