Vous êtes sur la page 1sur 22

1.

Création d'une base de données MySQL


Nous n'avons qu'une seule table. Créer une base de données
nommée Bookstore et une table nommée Book avec une structure
comme celle-ci:

2. Création d'un projet Eclipse avec Maven


Dans Eclipse IDE, cliquez sur Fichier> Nouveau> Projet Web
dynamique pour créer un nouveau projet Web dynamique
Java. Nommez le projet Bookstore:

N'oubliez pas de choisir le runtime cible comme Apache Tomcat


v8.0 et la version du module Web dynamique comme 3.1 (il
s'agit de la version du servlet Java).

Cliquez sur Terminer . Convertissez ensuite ce projet en


projet Maven en cliquant avec le bouton droit sur le projet,

84
sélectionnez Configurer> Convertir en projet Maven , comme
indiqué ci-dessous:

Vous devez saisir des informations pour créer le fichier POM


Maven, telles que l'ID de groupe, l'ID d'artefact, etc.
Ajoutez ensuite les dépendances suivantes
au fichier pom.xml :

<font style="vertical-align: inherit;"><font style="vertical-align:


inherit;"><dépendances></font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
<dépendance></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<groupId> javax.servlet </groupId></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
<artifactId> javax.servlet-api
</artifactId></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<version> 3.1.0 </version></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
<scope> fourni </scope></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
</dependency></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<dépendance></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<groupId> javax.servlet.jsp
</groupId></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<artifactId> javax.servlet.jsp-api
</artifactId></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<version> 2.3.1 </version></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
<scope> fourni </scope></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
</dependency></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<dépendance></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<groupId> jstl </groupId></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">

85
<artifactId> jstl </artifactId></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
<version> 1.2 </version></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
</dependency></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<dépendance></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<groupId> mysql </groupId></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
<artifactId> mysql-connector-java
</artifactId></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
<version> 5.1.30 </version></font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
</dependency></font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
</dependencies> </font></font>

Comme vous pouvez le voir, les dépendances sont ici pour


Servlet, JSP, JSTL et MySQL Connector Java (un pilote JDBC
pour MySQL).

Et n'oubliez pas de créer un package Java pour le projet, nous


utilisons ici le nom du package net.codejava.javaee.bookstore .

3. Classe de modèle d'écriture


Ensuite, créez une classe Java nommée Book.java pour modéliser
une entité book dans la base de données avec le code suivant:

<font style="vertical-align: inherit;"><font style="vertical-align:


inherit;">package net.codejava.javaee.bookstore;</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
/ **</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
* Book.java</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
* Il s'agit d'une classe modèle qui représente une entité
comptable</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
* @author www.codejava.net</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
*</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
* /</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
Livre de classe publique {</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
int int protégé;</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">

86
titre de chaîne protégé;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
auteur de chaîne protégé;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
prix flottant protégé;</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
Livre public () {</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
Livre public (int id) {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.id = id;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
Public book (int id, String title, String author, float price)
{</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
ceci (titre, auteur, prix);</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.id = id;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
Livre public (titre de la chaîne, auteur de la chaîne, prix flottant)
{</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
this.title = title;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.author = author;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.price = prix;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public int getId () {</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
id de retour;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public void setId (int id) {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.id = id;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>

87
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public String getTitle () {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
titre de retour;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public void setTitle (String title) {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.title = title;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public String getAuthor () {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
retour auteur;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public void setAuthor (auteur de la chaîne)
{</font></font><font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
this.author = author;</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
float public getPrice () {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
prix de retour;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font style="vertical-
align: inherit;">
public void setPrice (prix flottant) {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
this.price = prix;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
}</font></font>
Comme vous pouvez le voir, cette classe a 4 champs selon 4
colonnes dans la table book dans la base de données: id,
titre, auteur et prix.

88
4. Codage de la classe DAO
Ensuite, nous devons implémenter une classe DAO (Data Access
Layer) qui fournit des opérations CRUD (Créer, Lire, Mettre à
jour, Supprimer) pour le book table dans la base de
données. Voici le code source complet de la classe BookDAO :

package net.codejava.javaee.bookstore;<font></font>
<font></font>
import java.sql.Connection;<font></font>
import java.sql.DriverManager;<font></font>
import java.sql.PreparedStatement;<font></font>
import java.sql.ResultSet;<font></font>
import java.sql.SQLException;<font></font>
import java.sql.Statement;<font></font>
import java.util.ArrayList;<font></font>
import java.util.List;<font></font>
<font></font>
/**<font></font>
* AbstractDAO.java<font></font>
* This DAO class provides CRUD database operations for the table
book<font></font>
* in the database.<font></font>
* @author www.codejava.net<font></font>
*<font></font>
*/<font></font>
public class BookDAO {<font></font>
private String jdbcURL;<font></font>
private String jdbcUsername;<font></font>
private String jdbcPassword;<font></font>
private Connection jdbcConnection;<font></font>
<font></font>
public BookDAO(String jdbcURL, String jdbcUsername, String
jdbcPassword) {<font></font>
this.jdbcURL = jdbcURL;<font></font>
this.jdbcUsername = jdbcUsername;<font></font>
this.jdbcPassword = jdbcPassword;<font></font>
}<font></font>
<font></font>
protected void connect() throws SQLException {<font></font>
if (jdbcConnection == null || jdbcConnection.isClosed())
{<font></font>
try {<font></font>
Class.forName("com.mysql.jdbc.Driver");<font></font>
} catch (ClassNotFoundException e) {<font></font>
throw new SQLException(e);<font></font>
}<font></font>
jdbcConnection = DriverManager.getConnection(<font></font>
jdbcURL, jdbcUsername,
jdbcPassword);<font></font>
}<font></font>
}<font></font>
<font></font>

89
protected void disconnect() throws SQLException {<font></font>
if (jdbcConnection != null && !jdbcConnection.isClosed())
{<font></font>
jdbcConnection.close();<font></font>
}<font></font>
}<font></font>
<font></font>
public boolean insertBook(Book book) throws SQLException {<font></font>
String sql = "INSERT INTO book (title, author, price) VALUES (?, ?,
?)";<font></font>
connect();<font></font>
<font></font>
PreparedStatement statement =
jdbcConnection.prepareStatement(sql);<font></font>
statement.setString(1, book.getTitle());<font></font>
statement.setString(2, book.getAuthor());<font></font>
statement.setFloat(3, book.getPrice());<font></font>
<font></font>
boolean rowInserted = statement.executeUpdate() > 0;<font></font>
statement.close();<font></font>
disconnect();<font></font>
return rowInserted;<font></font>
}<font></font>
<font></font>
public List<Book> listAllBooks() throws SQLException {<font></font>
List<Book> listBook = new ArrayList<>();<font></font>
<font></font>
String sql = "SELECT * FROM book";<font></font>
<font></font>
connect();<font></font>
<font></font>
Statement statement =
jdbcConnection.createStatement();<font></font>
ResultSet resultSet = statement.executeQuery(sql);<font></font>
<font></font>
while (resultSet.next()) {<font></font>
int id = resultSet.getInt("book_id");<font></font>
String title = resultSet.getString("title");<font></font>
String author = resultSet.getString("author");<font></font>
float price = resultSet.getFloat("price");<font></font>
<font></font>
Book book = new Book(id, title, author, price);<font></font>
listBook.add(book);<font></font>
}<font></font>
<font></font>
resultSet.close();<font></font>
statement.close();<font></font>
<font></font>
disconnect();<font></font>
<font></font>
return listBook;<font></font>
}<font></font>
<font></font>

90
public boolean deleteBook(Book book) throws SQLException {<font></font>
String sql = "DELETE FROM book where book_id = ?";<font></font>
<font></font>
connect();<font></font>
<font></font>
PreparedStatement statement =
jdbcConnection.prepareStatement(sql);<font></font>
statement.setInt(1, book.getId());<font></font>
<font></font>
boolean rowDeleted = statement.executeUpdate() > 0;<font></font>
statement.close();<font></font>
disconnect();<font></font>
return rowDeleted; <font></font>
}<font></font>
<font></font>
public boolean updateBook(Book book) throws SQLException {<font></font>
String sql = "UPDATE book SET title = ?, author = ?, price =
?";<font></font>
sql += " WHERE book_id = ?";<font></font>
connect();<font></font>
<font></font>
PreparedStatement statement =
jdbcConnection.prepareStatement(sql);<font></font>
statement.setString(1, book.getTitle());<font></font>
statement.setString(2, book.getAuthor());<font></font>
statement.setFloat(3, book.getPrice());<font></font>
statement.setInt(4, book.getId());<font></font>
<font></font>
boolean rowUpdated = statement.executeUpdate() > 0;<font></font>
statement.close();<font></font>
disconnect();<font></font>
return rowUpdated; <font></font>
}<font></font>
<font></font>
public Book getBook(int id) throws SQLException {<font></font>
Book book = null;<font></font>
String sql = "SELECT * FROM book WHERE book_id = ?";<font></font>
<font></font>
connect();<font></font>
<font></font>
PreparedStatement statement =
jdbcConnection.prepareStatement(sql);<font></font>
statement.setInt(1, id);<font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
ResultSet resultSet = statement.executeQuery
();</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
if (resultSet.next ()) {</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">

91
String title = resultSet.getString
("title");</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
String author = resultSet.getString
("author");</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
float price = resultSet.getFloat
("prix");</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
livre = nouveau livre (id, titre, auteur,
prix);</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
resultSet.close ();</font></font><font></font><font
style="vertical-align: inherit;"><font style="vertical-align: inherit;">
statement.close ();</font></font><font></font>
<font></font><font style="vertical-align: inherit;"><font
style="vertical-align: inherit;">
livre de retour;</font></font><font></font><font style="vertical-
align: inherit;"><font style="vertical-align: inherit;">
}</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
}</font></font>

Comme vous pouvez le voir, les informations de connexion JDBC


sont injectées dans cette classe via son constructeur. Et les
méthodes suivantes s'appliquent aux opérations CRUD:

Créer: insertBook (Book) - ceci insère une nouvelle ligne


dans le book table .

Lire: listAllBooks () - cela récupère toutes les


lignes; et getBook (id) - renvoie une ligne spécifique en
fonction de la valeur de clé primaire (ID).

Update: updateBook (Book) - cela met à jour une ligne


existante dans la base de données.

Supprimer: deleteBook (Book) - cela supprime une ligne


existante dans la base de données en fonction de la
valeur de la clé primaire (ID).

Pour des instructions détaillées sur les opérations CRUD avec


JDBC, voir exemples d'insertion, de sélection, de mise à jour
et de suppression SQL .

92
5. Écriture d'une page JSP
Ensuite, créez une page JSP pour afficher tous les books de la
base de données. Voici le code de la page BookList.jsp sous
le répertoire WebContent dans le projet:

<font style="vertical-align: inherit;"><font style="vertical-align:


inherit;"><% @ page language = "java" contentType = "text / html; charset =
UTF-8"</font></font><font></font><font style="vertical-align:
inherit;"><font style="vertical-align: inherit;">
pageEncoding = "UTF-8"%></font></font><font></font>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><font></font>
<html><font></font>
<head><font></font>
<title>Books Store Application</title><font></font>
</head><font></font>
<body><font></font>
<center><font></font>
<h1>Books Management</h1><font></font>
<h2><font></font>
<a href="/new">Add New Book</a><font></font>
&nbsp;&nbsp;&nbsp;<font></font>
<a href="/list">List All Books</a><font></font>
<font></font>
</h2><font></font>
</center><font></font>
<div align="center"><font></font>
<table border="1" cellpadding="5"><font></font>
<caption><h2>List of Books</h2></caption><font></font>
<tr><font></font>
<th>ID</th><font></font>
<th>Title</th><font></font>
<th>Author</th><font></font>
<th>Price</th><font></font>
<th>Actions</th><font></font>
</tr><font></font>
<c:forEach var="book" items="${listBook}"><font></font>
<tr><font></font>
<td><c:out value="${book.id}" /></td><font></font>
<td><c:out value="${book.title}" /></td><font></font>
<td><c:out value="${book.author}" /></td><font></font>
<td><c:out value="${book.price}" /></td><font></font>
<td><font></font>
<a href="/edit?id=<c:out value='${book.id}'
/>">Edit</a><font></font>
&nbsp;&nbsp;&nbsp;&nbsp;<font></font>
<a href="/delete?id=<c:out value='${book.id}'
/>">Delete</a> <font></font>
</td><font></font>
</tr><font></font>
</c:forEach><font></font>
</table><font></font>

93
</div> <font></font>
</body><font></font>
</html>

Dans cette page JSP, nous utilisons JSTL pour afficher les
enregistrements du book table à partir de la base de
données. L' objet listBook sera transmis à partir d'un servlet
que nous créerons plus tard.

En cours d'exécution, cette page ressemble à ceci:

Comme vous pouvez le voir, sur cette page, nous avons deux
hyperliens dans le menu supérieur pour créer un nouveau livre
( Ajouter un nouveau livre Add new book ) et afficher tous les
livres ( Liste de tous les livres List All books ). De plus,
pour chaque livre individuel, il existe deux liens pour
l'édition ( Éditer Edit ) et la suppression ( Supprimer
Delet).

6. Page JSP de formulaire de livre d'écriture


Ensuite, nous créons une page JSP pour créer un nouveau livre
appelé BookForm.jsp . Voici son code source complet:

94
<%@ page language="java" contentType="text/html; charset=UTF-
8"<font></font>
pageEncoding="UTF-8"%><font></font>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%><font></font>
<html><font></font>
<head><font></font>
<title>Books Store Application</title><font></font>
</head><font></font>
<body><font></font>
<center><font></font>
<h1>Books Management</h1><font></font>
<h2><font></font>
<a href="/new">Add New Book</a><font></font>
&nbsp;&nbsp;&nbsp;<font></font>
<a href="/list">List All Books</a><font></font>
<font></font>
</h2><font></font>
</center><font></font>
<div align="center"><font></font>
<c:if test="${book != null}"><font></font>
<form action="update" method="post"><font></font>
</c:if><font></font>
<c:if test="${book == null}"><font></font>
<form action="insert" method="post"><font></font>
</c:if><font></font>
<table border="1" cellpadding="5"><font></font>
<caption><font></font>
<h2><font></font>
<c:if test="${book != null}"><font></font>
Edit Book<font></font>
</c:if><font></font>
<c:if test="${book == null}"><font></font>
Add New Book<font></font>
</c:if><font></font>
</h2><font></font>
</caption><font></font>
<c:if test="${book != null}"><font></font>
<input type="hidden" name="id"
value="<c:out value='${book.id}' />" /><font></font>
</c:if> <font></font>
<tr><font></font>
<th>Title: </th><font></font>
<td><font></font>
<input type="text" name="title" size="45"<font></font>
value="<c:out value='${book.title}'
/>"<font></font>
/><font></font>
</td><font></font>
</tr><font></font>
<tr><font></font>
<th>Author: </th><font></font>
<td><font></font>

95
<input type="text" name="author" size="45"<font></font>
value="<c:out value='${book.author}'
/>"<font></font>
/><font></font>
</td><font></font>
</tr><font></font>
<tr><font></font>
<th>Price: </th><font></font>
<td><font></font>
<input type="text" name="price" size="5"<font></font>
value="<c:out value='${book.price}'
/>"<font></font>
/><font></font>
</td><font></font>
</tr><font></font>
<tr><font></font>
<td colspan="2" align="center"><font></font>
<input type="submit" value="Save" /><font></font>
</td><font></font>
</tr><font></font>
</table><font></font>
</form><font></font>
</div> <font></font>
</body><font></font>
</html>

Cette page servira à la fois à créer un nouveau livre et à


modifier un livre existant. En mode édition, la servlet
transmettra un objet Book à la demande et nous utilisons
la balise <c: if> du JSTL pour déterminer si cet objet est
disponible ou non. S'il est disponible (non nul), le
formulaire est en mode édition, sinon il est en mode création.

Lors l'exécution, cette page affiche un nouveau formulaire


comme celui-ci:

96
Et en mode édition:

Nous verrons comment connecter la classe DAO aux pages JSP en


fonction des demandes des utilisateurs dans la section
suivante: créer la classe de servlet.

7. servlet de contrôleur de codage


Maintenant, la partie la plus difficile mais intéressante est
d'implémenter un servlet Java qui agit comme un contrôleur de
page pour gérer toutes les demandes du client. Regardons
d'abord le code:

package net.codejava.javaee.bookstore;<font></font>
<font></font>
import java.io.IOException;<font></font>
import java.sql.SQLException;<font></font>
import java.util.List;<font></font>
<font></font>
import javax.servlet.RequestDispatcher;<font></font>
import javax.servlet.ServletException;<font></font>
import javax.servlet.http.HttpServlet;<font></font>
import javax.servlet.http.HttpServletRequest;<font></font>
import javax.servlet.http.HttpServletResponse;<font></font>
<font></font>
/**<font></font>
* ControllerServlet.java<font></font>
* This servlet acts as a page controller for the application, handling
all<font></font>
* requests from the user.<font></font>
* @author www.codejava.net<font></font>
*/<font></font>

97
public class ControllerServlet extends HttpServlet {<font></font>
private static final long serialVersionUID = 1L;<font></font>
private BookDAO bookDAO;<font></font>
<font></font>
public void init() {<font></font>
String jdbcURL =
getServletContext().getInitParameter("jdbcURL");<font></font>
String jdbcUsername =
getServletContext().getInitParameter("jdbcUsername");<font></font>
String jdbcPassword =
getServletContext().getInitParameter("jdbcPassword");<font></font>
<font></font>
bookDAO = new BookDAO(jdbcURL, jdbcUsername,
jdbcPassword);<font></font>
<font></font>
}<font></font>
<font></font>
protected void doPost(HttpServletRequest request, HttpServletResponse
response)<font></font>
throws ServletException, IOException {<font></font>
doGet(request, response);<font></font>
}<font></font>
<font></font>
protected void doGet(HttpServletRequest request, HttpServletResponse
response)<font></font>
throws ServletException, IOException {<font></font>
String action = request.getServletPath();<font></font>
<font></font>
try {<font></font>
switch (action) {<font></font>
case "/new":<font></font>
showNewForm(request, response);<font></font>
break;<font></font>
case "/insert":<font></font>
insertBook(request, response);<font></font>
break;<font></font>
case "/delete":<font></font>
deleteBook(request, response);<font></font>
break;<font></font>
case "/edit":<font></font>
showEditForm(request, response);<font></font>
break;<font></font>
case "/update":<font></font>
updateBook(request, response);<font></font>
break;<font></font>
default:<font></font>
listBook(request, response);<font></font>
break;<font></font>
}<font></font>
} catch (SQLException ex) {<font></font>
throw new ServletException(ex);<font></font>
}<font></font>
}<font></font>

98
<font></font>
private void listBook(HttpServletRequest request, HttpServletResponse
response)<font></font>
throws SQLException, IOException, ServletException
{<font></font>
List<Book> listBook = bookDAO.listAllBooks();<font></font>
request.setAttribute("listBook", listBook);<font></font>
RequestDispatcher dispatcher =
request.getRequestDispatcher("BookList.jsp");<font></font>
dispatcher.forward(request, response);<font></font>
}<font></font>
<font></font>
private void showNewForm(HttpServletRequest request,
HttpServletResponse response)<font></font>
throws ServletException, IOException {<font></font>
RequestDispatcher dispatcher =
request.getRequestDispatcher("BookForm.jsp");<font></font>
dispatcher.forward(request, response);<font></font>
}<font></font>
<font></font>
private void showEditForm(HttpServletRequest request,
HttpServletResponse response)<font></font>
throws SQLException, ServletException, IOException
{<font></font>
int id = Integer.parseInt(request.getParameter("id"));<font></font>
Book existingBook = bookDAO.getBook(id);<font></font>
RequestDispatcher dispatcher =
request.getRequestDispatcher("BookForm.jsp");<font></font>
request.setAttribute("book", existingBook);<font></font>
dispatcher.forward(request, response);<font></font>
<font></font>
}<font></font>
<font></font>
private void insertBook(HttpServletRequest request, HttpServletResponse
response) <font></font>
throws SQLException, IOException {<font></font>
String title = request.getParameter("title");<font></font>
String author = request.getParameter("author");<font></font>
float price =
Float.parseFloat(request.getParameter("price"));<font></font>
<font></font>
Book newBook = new Book(title, author, price);<font></font>
bookDAO.insertBook(newBook);<font></font>
response.sendRedirect("list");<font></font>
}<font></font>
<font></font>
private void updateBook(HttpServletRequest request, HttpServletResponse
response) <font></font>
throws SQLException, IOException {<font></font>
int id = Integer.parseInt(request.getParameter("id"));<font></font>
String title = request.getParameter("title");<font></font>
String author = request.getParameter("author");<font></font>

99
float price =
Float.parseFloat(request.getParameter("price"));<font></font>
<font></font>
Book book = new Book(id, title, author, price);<font></font>
bookDAO.updateBook(book);<font></font>
response.sendRedirect("list");<font></font>
}<font></font>
<font></font>
private void deleteBook(HttpServletRequest request, HttpServletResponse
response) <font></font>
throws SQLException, IOException {<font></font>
int id = Integer.parseInt(request.getParameter("id"));<font></font>
<font></font>
Book book = new Book(id);<font></font>
bookDAO.deleteBook(book);<font></font>
response.sendRedirect("list");<font></font>
<font></font>
}<font></font>
}

Tout d'abord, regardez la méthode init () qui instancie une


instance de la classe BookDAO lorsque la servlet est instanciée
pour la première fois. Les informations de connexion JDBC
seront lues à partir des paramètres de contexte de
Servlet. Cette méthode n'est invoquée qu'une seule fois
pendant le cycle de vie de la servlet, il est donc raisonnable
de mettre le code d'instanciation DAO ici:.

public void init() {<font></font>


String jdbcURL =
getServletContext().getInitParameter("jdbcURL");<font></font>
String jdbcUsername =
getServletContext().getInitParameter("jdbcUsername");<font></font>
String jdbcPassword =
getServletContext().getInitParameter("jdbcPassword");<font></font>
<font></font>
bookDAO = new BookDAO(jdbcURL, jdbcUsername,
jdbcPassword);<font></font>
<font></font>
}
Ensuite, nous pouvons voir cette poignée de servlet à
la fois GET et POST demandes que la doPost () méthode invoque
la doGet () qui gère toute la demande:

protected void doGet(HttpServletRequest request, HttpServletResponse


response)<font></font>
throws ServletException, IOException {<font></font>
String action = request.getServletPath();<font></font>
<font></font>
try {<font></font>
switch (action) {<font></font>
case "/new":<font></font>

100
showNewForm(request, response);<font></font>
break;<font></font>
case "/insert":<font></font>
insertBook(request, response);<font></font>
break;<font></font>
case "/delete":<font></font>
deleteBook(request, response);<font></font>
break;<font></font>
case "/edit":<font></font>
showEditForm(request, response);<font></font>
break;<font></font>
case "/update":<font></font>
updateBook(request, response);<font></font>
break;<font></font>
default:<font></font>
listBook(request, response);<font></font>
break;<font></font>
}<font></font>
} catch (SQLException ex) {<font></font>
throw new ServletException(ex);<font></font>
}<font></font>
}
En fonction de l'URL de la demande (commence par / edit, /
list, / new, etc.), la servlet appelle les méthodes
correspondantes. Ici, nous examinons une méthode par exemple:

private void listBook(HttpServletRequest request, HttpServletResponse


response)<font></font>
throws SQLException, IOException, ServletException {<font></font>
List<Book> listBook = bookDAO.listAllBooks();<font></font>
request.setAttribute("listBook", listBook);<font></font>
RequestDispatcher dispatcher =
request.getRequestDispatcher("BookList.jsp");<font></font>
dispatcher.forward(request, response);<font></font>
}
Cette méthode utilise la classe DAO pour récupérer tous les
livres de la base de données, puis les transmettre à
la page BookList.jsp pour afficher le résultat. Une logique
similaire est implémentée pour les autres méthodes.

8. Configuration de Web.xml
Pour que le ControllerServlet intercepte toutes les demandes,
nous devons configurer son mappage dans le fichier descripteur
de déploiement Web web.xml . Ouvrez le fichier web.xml sous
le répertoire WebContent \ WEB-INF et mettez-le à jour avec le code
suivant:

<?xml version="1.0" encoding="UTF-8"?><font></font>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<font></font>
xmlns="http://xmlns.jcp.org/xml/ns/javaee"<font></font>
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee <font></font>
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"<font></font>

101
id="WebApp_ID" version="3.1"><font></font>
<display-name>Books Management Web Application</display-
name><font></font>
<font></font>
<context-param><font></font>
<param-name>jdbcURL</param-name><font></font>
<param-value>jdbc:mysql://localhost:3306/bookstore</param-
value><font></font>
</context-param><font></font>
<font></font>
<context-param><font></font>
<param-name>jdbcUsername</param-name><font></font>
<param-value>root</param-value><font></font>
</context-param><font></font>
<font></font>
<context-param><font></font>
<param-name>jdbcPassword</param-name><font></font>
<param-value>P@ssw0rd</param-value><font></font>
</context-param><font></font>
<font></font>
<servlet><font></font>
<servlet-name>ControllerServlet</servlet-name><font></font>
<servlet-
class>net.codejava.javaee.bookstore.ControllerServlet</servlet-
class><font></font>
</servlet><font></font>
<font></font>
<servlet-mapping><font></font>
<servlet-name>ControllerServlet</servlet-name><font></font>
<url-pattern>/</url-pattern><font></font>
</servlet-mapping><font></font>
<font></font>
<error-page><font></font>
<exception-type>java.lang.Exception</exception-type><font></font>
<location>/Error.jsp</location><font></font>
</error-page><font></font>
</web-app>

Comme vous pouvez le voir, les éléments <context-


param> spécifient les informations de connexion JDBC (URL, nom
d'utilisateur et mot de passe) pour la classe DAO.

Les éléments <servlet> et <servlet-mapping> déclarent et spécifient


le mappage d'URL pour la classe ControllerServlet . Le modèle
d'URL / signifie qu'il s'agit du servlet par défaut pour gérer
toutes les demandes.

Les éléments de page <error> spécifient la page de gestion des


erreurs pour toutes sortes d'exceptions ( java.lang.Exception )
qui peuvent survenir pendant la durée de vie de l'application.

102
9. Écriture de la page JSP d'erreur
Voici le code de la page Error.jsp qui affiche simplement le
message d'exception:

<%@ page language="java" contentType="text/html; charset=UTF-


8"<font></font>
pageEncoding="UTF-8" isErrorPage="true" %><font></font>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<font></font>
"http://www.w3.org/TR/html4/loose.dtd"><font></font>
<html><font></font>
<head><font></font>
<title>Error</title><font></font>
</head><font></font>
<body><font></font>
<center><font></font>
<h1>Error</h1><font></font>
<h2><%=exception.getMessage() %><br/> </h2><font></font>
</center> <font></font>
</body><font></font>
</html>
Cela ressemble à ceci lorsqu'une erreur se produit:

10. Déploiement et test de l'application


Jusqu'à présent, nous avons terminé le code du projet. Il est
temps de déployer et de tester l'application pour voir comment
cela fonctionne.

Tapez l'URL suivante dans votre navigateur Web pour accéder à


l'application Librairie:

http: // localhost: 8080 / bookstore

La première fois, la liste est vide car il n'y a pas encore de


livre:

103
Cliquez sur l'hyperlien Ajouter un nouveau livre pour commencer à
ajouter un nouveau livre:

Saisissez les informations du livre (titre, auteur et prix) et


cliquez sur Enregistrer . L'application enregistre le livre et
affiche la liste, comme indiqué ci-dessous:

104
Dans cette liste, vous pouvez cliquer sur
les hyperliens Modifier et supprimer pour modifier et supprimer
un livre spécifique.

105

Vous aimerez peut-être aussi