Vous êtes sur la page 1sur 13

NOM : ABDERREZAK

Prénom: AbdelMounaim

Classe: GMI2

Compte Rendu TP 3 :

Objectif(s) du TP :

s'entraîner avec Hibernate .

Encadré par  :
Mme.Sbai

2019 - 2020
TP 3  : Article

metier :
Class Article :
package metier;

import java.util.Date;

public class Article {

private Long numArticle;


private String nomAuteur;
private String contenu;
private String photo;
private Date datePublication;

public Article() {

public Article(String nomAuteur, String contenu, String photo, Date


datePublication) {
super();
this.nomAuteur = nomAuteur;
this.contenu = contenu;
this.photo = photo;
this.datePublication = datePublication;
}

public Long getNumArticle() {


return numArticle;
}

public void setNumArticle(Long numArticle) {


this.numArticle = numArticle;
}

public String getNomAuteur() {


return nomAuteur;
}

public void setNomAuteur(String nomAuteur) {


this.nomAuteur = nomAuteur;
}

public String getContenu() {


return contenu;
}

public void setContenu(String contenu) {


this.contenu = contenu;
}

public String getPhoto() {


return photo;
}

public void setPhoto(String photo) {


this.photo = photo;
}

public Date getDatePublication() {


return datePublication;
}

public void setDatePublication(Date datePublication) {


this.datePublication = datePublication;
}

@Override
public String toString() {
return "Article [numArticle=" + numArticle + ", nomAuteur=" +
nomAuteur + ", contenu=" + contenu + ", photo="
+ photo + ", datePublication=" + datePublication + "]";
}

Interface IJournalMetier :
package metier;

import java.util.List;

public interface IjournalMetier {

public void ajouterArticle(Article a);

public List<Article> consulterArticles();

public List<Article> consulterArticlesParMC(String mc);

public void supprimerArticle(Long numArt);

public Article getArticle(Long numArt);

public void updateArticle(Article a);

}
Class IJournalMetierImpl :
package metier;

import java.util.List;

import org.hibernate.Session;

import util.HibernateUtil;

import org.hibernate.Query;

public class JournalMetierImpl implements IjournalMetier {

@Override
public void ajouterArticle(Article a) {

//Creer L'objet Session Factory


Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//commencer un transaction
session.beginTransaction();
//appeler la méthode ajouter (save)
session.save(a);

//valider la transaction
session.getTransaction().commit();

@Override
public List<Article> consulterArticles() {
//créer l'objet session factory
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//commencer un transaction
session.beginTransaction();

//la requete sql


Query requete = session.createQuery("select a from articles ");

//recuperer la liste
List<Article> articles = requete.list();

//valider la transaction
session.getTransaction().commit();

return articles;
}

@Override
public List<Article> consulterArticlesParMC(String mc) {

//créer l'objet session factory


Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//commencer un transaction
session.beginTransaction();

//la requete sql


Query requete = session.createQuery("select a from articles a where a.nom like
:x");

//remplacer x
requete.setParameter("x", "%"+mc+"%");

//recuperer la liste
List<Article> articles = requete.list();

//valider la transaction
session.getTransaction().commit();

return articles;
}

@Override
public void supprimerArticle(Long numArt) {

//Creer L'objet Session Factory


Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//commencer un transaction
session.beginTransaction();

//créer un objet
Object a = session.get(Article.class, numArt);
//test l'objet
if(a==null) throw new RuntimeException("Produit introuvable");
//appliquer la méthode delete
session.delete(a);

//valider la transaction
session.getTransaction().commit();

@Override
public Article getArticle(Long numArt) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//créer un objet
Object a = session.get(Article.class, numArt);
//test l'objet
if(a==null) throw new RuntimeException("Produit introuvable");
return (Article) a;
}

@Override
public void updateArticle(Article a) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.update(a);
session.getTransaction().commit();

Mapping :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="metier">

<class name="metier.Article" table="articles">


<id name="numArticle" column="NUM_ART">
<generator class="native"></generator>
</id>

<property name="nomAuteur" column="nom"></property>


<property name="contenu" column="contenu"></property>
<property name="photo" column="photo"></property>
<property name="datePublication" column="date"></property>

</class>

</hibernate-mapping>

util :
Class HibernateUtil :
package util;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

public static final SessionFactory sessionFactory;


static {
try {
//creation de la SessionFactory a partir de Hibernate.cfg.xml
sessionFactory = new
Configuration().configure("Hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex) {
System.err.println("Initial SessionFactory creation failed." +ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}

Web :
Class Model :
package web;

import java.util.ArrayList;
import java.util.List;

import metier.Article;

public class Model {

private String motcle;


private String erreur;
private String mode="ajout";
// pour saisir le motclé
private Article article=new Article();
private List<Article> articles=new ArrayList<Article>();

public String getMotcle() {


return motcle;
}
public void setMotcle(String motcle) {
this.motcle = motcle;
}
public String getErreur() {
return erreur;
}
public void setErreur(String erreur) {
this.erreur = erreur;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}

Class ControleurServlet:
package web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import metier.Article;
import metier.IjournalMetier;
import metier.JournalMetierImpl;
import metier.Produit;

public class ControleurServlet extends HttpServlet{

private IjournalMetier metier;

@Override
public void init() throws ServletException {
metier= new JournalMetierImpl();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
doPost(request,response);//centraliser le tt dans la méthode post
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

Model model=new Model(); //MODEL


request.setAttribute("modele",model);
String action=request.getParameter("action");

if (action!=null) {

if(action.equals("chercher")) {

model.setMotcle(request.getParameter("motCle"));
List<Article>
articles=metier.consulterArticlesParMC(model.getMotcle());
model.setArticles(articles);
}

else if (action.equals("delete")) {

Long
ref=(long)Integer.parseInt(request.getParameter("ref")) ;
metier.supprimerArticle(ref);
model.setArticles(metier.consulterArticles());

else if (action.equals("editer")) {

Long
ref=(long)Integer.parseInt(request.getParameter("ref")) ;
Article p=metier.getArticle(ref);
model.setArticle(p);
model.setMode("edit");
model.setArticles(metier.consulterArticles());
}

else if (action.equals("ajouter")) {

try {

model.getArticle().setNomAuteur((request.getParameter("nom")));

model.getArticle().setContenu((request.getParameter("contenu")));

model.getArticle().setPhoto((request.getParameter("photo")));
SimpleDateFormat format = new SimpleDateFormat("MMMM-dd-
yyyy",Locale.ENGLISH) ;
model.getArticle().setDatePublication(format.parse(request.getParameter("date")) )
;
//model.getArticle().setDatePublication(new Date());
model.setMode(request.getParameter("mode"));

if(model.getMode().equals("ajout"))

metier.ajouterArticle(model.getArticle());

else if (model.getMode().equals("edit"))
metier.updateArticle(model.getArticle());

model.setArticles(metier.consulterArticles());
}
catch (Exception e){
model.setErreur(e.getMessage());

}
}
//redirection a la page jsp
request.getRequestDispatcher("VueArticle.jsp").forward(request,
response);

Hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_articles</property
>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">saramounaim</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property
name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource ="metier/Article.hbm.xml"/>
</session-factory>
</hibernate-configuration>
JSP :
Page html VueArticle:
<%@page import="metier.Article"%><%@page import="java.util.List"%>
<%@page import="web.Model"%>
<%
Model mod;
if(request.getAttribute("modele")!=null){
mod=(Model)request.getAttribute("modele");
}
else{ mod=new Model(); }
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript">
function confirmer(url){
var rep=confirm("etes vous sûres de vouloir supprimer")
if (rep==true){
document.location=url;
}
}
</script>
</head>
<body>
<div>
<form action="controleur.php" method="post">
<table>
<tr>
<td> Motclé </td>
<td> <input type="text" name="motCle" value="<%=mod.getMotcle() %>" /> </td>
<td> <input type="submit" value="chercher" name="action"/> </td>
</tr>
</table>
</form>
</div>
<div>
<%= mod.getErreur() %>
</div>
<div>
<div>
<form action="controleur.php" method="post">
<input type="text" value="<%=mod.getMode()%>" name="mode">
<table>
<%
if (mod.getMode().equals("ajout"))
{
%>
<tr>
<td> REF </td>
<td> <input type="text" name="numArticle" value="<%=
mod.getArticle().getNumArticle()%>" /> </td>
<td></td>
</tr>
<% } %>
<%
if (mod.getMode().equals("edit"))
{
%>
<tr>
<td> REF </td>
<td> <%= mod.getArticle().getNumArticle()%><input type="hidden" name="numArticle"
value="<%= mod.getArticle().getNumArticle()%>" /> </td>
<td></td>
</tr>
<% } %>
<tr>
<td> nom </td>
<td> <input type="text" name="nomAuteur" value="<%=
mod.getArticle().getNomAuteur()%>" /> </td>
<td></td>
</tr>
<tr>
<td> contenu </td>
<td> <input type="text" name="contenu" value="<%= mod.getArticle().getContenu()
%>" /> </td>
<td></td>
</tr>
<tr>
<td> photo </td>
<td> <input type="text" name="Quantite" value="<%= mod.getArticle().getPhoto() %>"
/> </td>
<td></td>
</tr>
<tr>
<td> date </td>
<td> <input type="text" name="datePublication" value="<%=
mod.getArticle().getDatePublication() %>" /> </td>
<td></td>
</tr>
<tr><td> <input type="submit" value="ajouter" name="action">
</tr>
</table>
</form>
</div>

<table class="table1">
<tr>
<th> REF </th> <th> nom </th> <th> contenu </th> <th> photo </th> <th> date
</th>
</tr>
<%
List<Article> articles=mod.getArticles();
for(Article a:articles){ %>
<tr>
<td><%=a.getNumArticle() %></td> <td><%=a.getNomAuteur() %></td>
<td><%=a.getContenu() %></td> <td><%=a.getPhoto() %></td>
<td><%=a.getDatePublication() %></td>
<td> <a href="javascript:confirmer('controleur.php?action=delete&ref=<
%=a.getNumArticle()%>')">supprimer</a></td>
<td> <a href="controleur.php?action=editer&ref=<%=a.getNumArticle()
%>">editer</a></td>
</tr>
<% } %>
</table>
</div>
</body>
</html>