Java EE salvare i dati su un database : in questa lezione realizzeremo una pagina web per registrare su un database MySQL un nuovo utente
- Creazione database
- Tabella utenti
- Pagina register.jsp
- Java Bean per i dati dell’utente
- Implementare il Connettore MySQL nel progetto
- Classe DAO (Data Access Objects)
- Servlet registrazione utente
Creazione database
Creiamo il db con il seguente comando SQL:
CREATE DATABASE myappdb;
Tabella utenti
CREATE TABLE users(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(60) NOT NULL,
lastname VARCHAR(60)NOT NULL,
email VARCHAR(60) NOT NULL,
password VARCHAR(256) NOT NULL
);
E’ consigliabile creare un utente del DBMS con permessi ridotti come visto nella lezione MySQL Gestire utenti e permessi
Pagina register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register page</title>
</head>
<body>
<form action="RegisterServlet" method="POST">
<table>
<tr>
<td>Nome: </td>
<td><input type="text" name="first-name" maxlength="60"></td>
<td>Cognome: </td>
<td><input type="text" name="last-name" maxlength="60"></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="email" name="email" maxlength="60"></td>
<td>Password: </td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit"></td>
<td><input type="reset"></td>
</tr>
</table>
</form>
</body>
</html>
Java Bean
Creiamo il Java Bean che ci permette di conservare lo stato delle sue variabili per il tempo di utilizzo. Tale classe ha solo i getter ed i setter
Dopo aver creato la classe UserBean implementiamo l’interfaccia Serializable ed aggiungiamo un serial version ID generato

dopo aver creato gli attributi che rappresentano i dati di un utente generiamo automaticamente i setters ed i getters dal menu Source

La classe UserBean.java
package bean;
public class UserBean implements java.io.Serializable{
private static final long serialVersionUID = 3432068515031339999L;
private String firstName;
private String lastName;
private String email;
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Implementare il Connettore MySQL nel progetto
Scaricare il connettore MySQL per Java da questo MySQL Community Downloads scegliendo la versione Platform Indipendent

ora copia il connettore all’interno della cartella lib
che a sua volta è all’interno della cartella WEB-INF

Classe DAO (Data Access Objects)
Per gestire il CRUD (Create, Read, Update, Delete) del database
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import bean.UserBean;
public class DBManager {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:8889/myappdb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
private static Connection getDBConnection() throws Exception {
Connection dbConnection=null;
try {
Class.forName(DB_DRIVER);
}catch(ClassNotFoundException e) {
System.out.println("Driver NOT FOUND");
throw new Exception(e.getMessage());
}
try {
dbConnection=DriverManager.getConnection(DB_CONNECTION,DB_USER,DB_PASSWORD);
System.out.println("Connection OK");
}catch(SQLException e) {
System.out.println("Connection FAILED");
throw new SQLException(e.getErrorCode()+"");
}
return dbConnection;
}
public void insertUser(UserBean user) throws Exception {
Statement statement=null;
Connection conn=null;
try {
conn=getDBConnection();
conn.setAutoCommit(false);
statement=conn.createStatement();
String query = "INSERT INTO users (firstname,lastname,email,password)";
query +="VALUES ('"
+ user.getFirstName() + "' , '"
+ user.getLastName() + "' , '"
+ user.getEmail() + "' , '"
+ user.getPassword() + "')";
System.out.println("Inserimento utente");
statement.executeUpdate(query);
conn.commit();
}catch(SQLException e) {
if(conn!=null) {
conn.rollback();
System.out.println("INSERT ERROR: Transaction is being rolled back");
}
}finally {
if(statement != null) {
statement.close();
}
if(conn != null) {
conn.close();
}
}
}
public static void testConnection() throws Exception {
getDBConnection();
}
}
Servlet registrazione utente
package servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.RequestDispatcher;
import java.io.IOException;
import bean.UserBean;
import db.DBManager;
/**
* Servlet implementation class RegisterServlet
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
try {
// DbManager.testConnection();
String firstName = request.getParameter("first-name");
String lastName = request.getParameter("last-name");;
String email = request.getParameter("email");
String password = request.getParameter("password");
UserBean user=new UserBean();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setPassword(password);
DBManager dbManager=new DBManager();
dbManager.insertUser(user);
ServletContext sc = request.getSession().getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/insert-ok.jsp");
rd.forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Se l’inserimento dell’utente va a buon fine reindirizzeremo l’utente alla pagina jsp insert-ok.jsp utilizzando l’oggetto RequestDispatcher
Infine la pagina insert-ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registrazione ok</title>
</head>
<body>
L'utente è stato inserito correttamente
</body>
</html>
Java EE (Enterprise Edition) è una piattaforma di sviluppo per applicazioni aziendali che fornisce una vasta gamma di API (Application Programming Interface) per sviluppare applicazioni web e servizi distribuiti. MySQL, d’altra parte, è un sistema di gestione di database relazionali open source che può essere utilizzato come backend per le applicazioni sviluppate con Java EE. Insieme, Java EE e MySQL consentono di creare applicazioni web robuste e scalabili.
Ecco alcuni esempi di applicazioni che è possibile sviluppare utilizzando Java EE e MySQL:
- Siti web e portali: Java EE fornisce un’ampia gamma di API per sviluppare siti web dinamici, con funzionalità come la gestione delle sessioni, l’autenticazione degli utenti, la gestione dei dati, l’integrazione con servizi di terze parti, ecc. MySQL può essere utilizzato come backend per memorizzare i dati del sito web.
- Sistemi di gestione dei contenuti (CMS): Java EE può essere utilizzato per sviluppare un CMS personalizzato con funzionalità come la gestione dei contenuti, la creazione di pagine, la gestione degli utenti, ecc. MySQL può essere utilizzato come database per archiviare i contenuti del CMS.
- Applicazioni di e-commerce: Java EE fornisce API per sviluppare applicazioni di e-commerce con funzionalità come il carrello della spesa, l’elaborazione dei pagamenti, la gestione degli ordini, ecc. MySQL può essere utilizzato come database per memorizzare i prodotti, gli ordini e altre informazioni pertinenti.
- Applicazioni di gestione delle risorse umane: Java EE può essere utilizzato per sviluppare applicazioni di gestione delle risorse umane con funzionalità come la gestione dei dipendenti, la gestione delle ferie, la gestione delle prestazioni, ecc. MySQL può essere utilizzato come database per archiviare le informazioni sui dipendenti e le prestazioni.
- Applicazioni di business intelligence: Java EE può essere utilizzato per sviluppare applicazioni di business intelligence con funzionalità come la creazione di report, l’analisi dei dati, la visualizzazione dei dati, ecc. MySQL può essere utilizzato come database per archiviare i dati aziendali e per supportare l’analisi dei dati.
Questi sono solo alcuni esempi di applicazioni che possono essere sviluppate con Java EE e MySQL. La combinazione di queste due tecnologie offre una vasta gamma di funzionalità per lo sviluppo di applicazioni web e servizi distribuiti.