15 Fév2016
Ajax (JavaScript) avec JSP et Hibernate
Objectifs :
- Manipulation de AJAX avec JavaScript.
- Manipulation des requêtes nommées avec Hibernate.
- Développement des pages web avec JSP.
Énoncé :
On souhaite développer une page web JSP permettant de renvoyer les informations d'un utilisateur donné sans recharger toute la page (Voir figure ci-dessous).
Travail demandé :
-
Couche accès aux données avec Hibernate
- Créer l'entité User.
- Créer le fichier de configuration hibernate (hibernate.cfg.xml).
- Créer la classe HibernateUtil permettant de créer une SessionFactory.
- Créer l'interface IDao avec deux méthodes (findAll et findById).
- Créer la classe UserService qui implémente l'interface IDao.
- Créer un programme de Test pour tester les deux méthodes.
-
Couche présentation
- Créer la page web JSP suivante :
- Créer la fonction JavaScript permettant d’afficher les informations de la personne sélectionnée.
- Créer une page Web JSP contenant les informations d'une personne donnée. Cette page sera invoquée à partir de la fonction JavaScript.
Structure finale du projet
Couche accès aux données
-
Entity User
/** * * @author lachgar */ @Entity @Table(name = "user") @NamedQueries({ @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id")}) public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "FirstName") private String firstName; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "LastName") private String lastName; @Basic(optional = false) @NotNull @Column(name = "Age") private int age; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "Hometown") private String hometown; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "Job") private String job; public User() { } public User(Integer id) { this.id = id; } public User(Integer id, String firstName, String lastName, int age, String hometown, String job) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; this.hometown = hometown; this.job = job; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getHometown() { return hometown; } public void setHometown(String hometown) { this.hometown = hometown; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof User)) { return false; } User other = (User) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "ma.projet.entity.User[ id=" + id + " ]"; } }
-
Fichier de configuration hibernate (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.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my_db?zeroDateTimeBehavior=convertToNull</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="ma.projet.entity.User"/> </session-factory> </hibernate-configuration>
-
L'interface IDao
package ma.projet.dao; import java.util.List; public interface IDao <T> { T findById(int id); List <T> findAll(); }
-
La classe HibernateUtil
package ma.projet.util; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; /** * @author lachgar */ public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from standard (hibernate.cfg.xml) // config file. sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Log the exception. System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
-
La classe UserService
package ma.projet.service; import java.util.List; import ma.projet.dao.IDao; import ma.projet.entity.User; import ma.projet.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author lachgar */ public class UserService implements IDao<User> { private Session session; private Transaction tx; @Override public User findById(int id) { User u = null; session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); u = (User) session.getNamedQuery("User.findById").setParameter("id", id).uniqueResult(); return u; } @Override public List<User> findAll() { List <User> users = null; session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); users = session.getNamedQuery("User.findAll").list(); return users; } }
-
La classe de Test :
import ma.projet.entity.User; import ma.projet.service.UserService; /** * * @author lachgar */ public class Test { public static void main(String[] args) { UserService us = new UserService(); System.out.println("" + us.findById(1)); for (User u : us.findAll()) { System.out.println(u.getFirstName()); } } }
La couche présentation
-
La page web JSP "index.jsp"
<%-- Document : index Created on : 27 avr. 2015, 14:56:19 Author : lachgar --%> <%@page import="ma.projet.entity.User"%> <%@page import="java.util.List"%> <%@page import="ma.projet.service.UserService"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>AJAX avec JSP</title> <script src="/script.js" type="text/javascript"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select One</option> <% UserService us = new UserService(); List <User> users = us.findAll(); for(User u : users){ %> <option value="<%=u.getId() %>"> <%=u.getFirstName()+" "+u.getLastName() %></option> <%}%> </select> </form> <div id="info">Informations</div> </body> </html>
-
La fonction JavaScript
function showUser(str) { if (str == "") { document.getElementById("info").innerHTML = "R A S"; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", "list.jsp?q=" + str, true); xmlhttp.send(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("info").innerHTML = xmlhttp.responseText; } } }
-
La page Web JSP "list.jsp"
<%-- Document : list Created on : 27 avr. 2015, 15:03:27 Author : lachgar --%> <%@page import="ma.projet.entity.User"%> <%@page import="ma.projet.service.UserService"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% int id = Integer.parseInt(request.getParameter("q")); UserService us = new UserService(); User u = us.findById(id); %> <table border="1"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Home Town</th> <th>Job</th> </tr> </thead> <tbody> <tr> <td><%=u.getFirstName() %></td> <td><%=u.getLastName() %></td> <td><%=u.getAge() %></td> <td><%=u.getHometown() %></td> <td><%=u.getJob() %></td> </tr> </tbody> </table> </body> </html>