Problème d'affichage des données dans un combobox

Résolu/Fermé
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023 - Modifié le 18 juil. 2018 à 12:59
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023 - 22 juil. 2018 à 02:05
Bonjour à tous.Je dois afficher une liste de pays provenant de la base de données dans un combobox pour que l'utilisateur sélectionne le pays qu'il veut.Mais au chargement de la page la liste de pays n'est pas affichée.Ci-dessous le code source.mon frontend est du lteAdmin(bootstrap). J'ai besoin d'aide c'est urgent si quelqu'un pourra m'aider.Merci d'avance.

<%@page import="java.sql.SQLException"%>
<%@page import="javax.swing.JComboBox"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="sn.mobilebanking.utils.ConnectionDB"%>
<%@page import="java.sql.Connection"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

  <!--  Scriptlet: sélection des noms des pays -->
  <%
      Connection conn=ConnectionDB.getConnection();
       JComboBox comboPays=new JComboBox();
      String sql="SELECT pays_nom FROM pays";
      try
      {
       Statement st=conn.createStatement();
       ResultSet rs=st.executeQuery(sql);
       while(rs.next()){
        String nomPays=rs.getString("pays_nom");
       comboPays.addItem(nomPays);
       
       }
      }catch(SQLException e){
       e.printStackTrace();
      }
     
  %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajouter des pays</title>
<meta
 content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
 name='viewport'>
<!-- bootstrap 3.0.2 -->
<link
 href="${pageContext.request.contextPath }/assets/css/bootstrap.min.css"
 rel="stylesheet" type="text/css" />
<!-- font Awesome -->
<link
 href="${pageContext.request.contextPath }/assets/font-awesome.min.css"
 rel="stylesheet" type="text/css" />
<!-- Ionicons -->
<link
 href="${pageContext.request.contextPath }/assets/css/ionicons.min.css"
 rel="stylesheet" type="text/css" />
<!-- Morris chart -->
<link
 href="${pageContext.request.contextPath }/assets/css/morris/morris.css"
 rel="stylesheet" type="text/css" />
<!-- jvectormap -->
<link
 href="${pageContext.request.contextPath }/assets/css/jvectormap/jquery-jvectormap-1.2.2.css"
 rel="stylesheet" type="text/css" />
<!-- fullCalendar -->
<link
 href="${pageContext.request.contextPath }/assets/css/fullcalendar/fullcalendar.css"
 rel="stylesheet" type="text/css" />
<!-- Daterange picker -->
<link
 href="${pageContext.request.contextPath }/assets/css/daterangepicker/daterangepicker-bs3.css"
 rel="stylesheet" type="text/css" />
<!-- bootstrap wysihtml5 - text editor -->
<link
 href="${pageContext.request.contextPath }/assets/css/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css"
 rel="stylesheet" type="text/css" />
<!-- Theme style -->
<link href="${pageContext.request.contextPath }/assets/css/AdminLTE.css"
 rel="stylesheet" type="text/css" />

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
        <![endif]-->
</head>
<body class="skin-black">


   <!-- Main content -->
   <section class="content">
                   <div class="row">
                          <div class="col-md-8">
                          

      <!--  Formulaire d'insertion des clients -->
      <!-- quick email widget -->
      <div class="box box-info">
       <div class="box-header">
        <i class="fa fa-envelope"></i>
        <h3 class="box-title">Veuillez remplir les champs</h3>
        <!-- tools box -->
        <div class="pull-right box-tools">
         <button class="btn btn-info btn-sm" data-widget="remove"
          data-toggle="tooltip" title="Remove">
          <i class="fa fa-times"></i>
         </button>
        </div>
        <!-- /. tools -->
       </div>
       <div class="box-body">
        <form
         action=""
         method="post">
         <div class="form-group">
          <input id="nomClient" type="text" class="form-control"
           name="nomClient" placeholder="Nom du client" /> 
         </div>
         
         <div class="form-group">
          <label>Selectionner le pays</label> <select
           class="form-control combobox" name="" value="<%=comboPays %>">
          </select>
         </div>
         <div class="box-footer">
          <button type="submit" class="btn btn-primary">Enregistrer</button>
         </div>
        </form>
       </div>
       <!-- <div class="box-footer clearfix">
        <button class="pull-right btn btn-default" id="sendEmail">
         Send <i class="fa fa-arrow-circle-right"></i>
        </button>
       </div> -->
      </div>
                          </div>
                   </div>
     </section>
     
    </div>
    <!-- /.row (main row) -->

 
 
 <!-- ./wrapper -->

 <!-- add new calendar event modal -->


 <!-- jQuery 2.0.2 -->
 <script
  src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
 <!-- jQuery UI 1.10.3 -->
 <script
  src="${pageContext.request.contextPath }/assets/js/jquery-ui-1.10.3.min.js"
  type="text/javascript"></script>
 <!-- Bootstrap -->
 <script
  src="${pageContext.request.contextPath }/assets/js/bootstrap.min.js"
  type="text/javascript"></script>
 <!-- Morris.js charts -->
 <script
  src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/morris/morris.min.js"
  type="text/javascript"></script>
 <!-- Sparkline -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/sparkline/jquery.sparkline.min.js"
  type="text/javascript"></script>
 <!-- jvectormap -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"
  type="text/javascript"></script>
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"
  type="text/javascript"></script>
 <!-- fullCalendar -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/fullcalendar/fullcalendar.min.js"
  type="text/javascript"></script>
 <!-- jQuery Knob Chart -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/jqueryKnob/jquery.knob.js"
  type="text/javascript"></script>
 <!-- daterangepicker -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/daterangepicker/daterangepicker.js"
  type="text/javascript"></script>
 <!-- Bootstrap WYSIHTML5 -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"
  type="text/javascript"></script>
 <!-- iCheck -->
 <script
  src="${pageContext.request.contextPath }/assets/js/plugins/iCheck/icheck.min.js"
  type="text/javascript"></script>

 <!-- AdminLTE App -->
 <script
  src="${pageContext.request.contextPath }/assets/js/AdminLTE/app.js"
  type="text/javascript"></script>

 <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
 <script
  src="${pageContext.request.contextPath }/assets/js/AdminLTE/dashboard.js"
  type="text/javascript"></script>

</body>
</html>
A voir également:

2 réponses

KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
18 juil. 2018 à 13:19
Bonjour,

Pour commencer, les scriptlets c'est mal, le code Java devrait être dans un fichier Java, les JSP ne devraient être là que pour faire de l'affichage, pas pour appeler la base de données ou je ne sais quel traitement.

Quant à ton code,
comboPays
est un JComboBox de l'API Swing !!! Qu'est-ce que ça vient faire dans une JSP !?

<%@page import="javax.swing.JComboBox"%>
...
       JComboBox comboPays=new JComboBox();
...
          <label>Selectionner le pays</label> <select
           class="form-control combobox" name="" value="<%=comboPays %>">
          </select>

Le scriptlet
<%= %>
va afficher le toString de ce composant Swing, tu peux regarder le code HTML généré par ce morceau de code mais ça va te donner un truc un rallonge du genre :
javax.swing.JComboBox[, 0, 0, 0x0, invalid, layout=javax.swing.plaf.metal.MetalComboBoxUI$MetalComboBoxLayoutManager, alignmentX=0.0, alignmentY=0.0, border=, flags=328, maximumSize=, minimumSize=, preferredSize=, isEditable=false, lightWeightPopupEnabled=true, maximumRowCount=8, selectedItemReminder=]

Rien à voir donc avec un code HTML où l'on devrait trouver dans la balise
select
une liste de balises
option
:

<select>
    <option value="id_pays1">Pays1</option>
    <option value="id_pays2">Pays2</option>
    <option value="id_pays3">Pays3</option>
    <option value="id_pays4">Pays4</option>
</select>

Remarque : tu as un
catch(SQLException e) { e.printStackTrace(); }
dont il serait intéressant d'afficher un message d'erreur dans la JSP au cas où il y ait eu une erreur.
0
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
Modifié le 18 juil. 2018 à 21:29
<select>
    <option value="id_pays1">Pays1</option>
    <option value="id_pays2">Pays2</option>
    <option value="id_pays3">Pays3</option>
    <option value="id_pays4">Pays4</option>
</select>


Bonjour KX.Merci pour la réponse.Au fait avec cette portion de code les données sont statiques.Ce que je voudrais c'est afficher ces pays d'une manière dynamique(ces pays sont déjà enregistrés dans une table 'clients').Je peux écrire une méthode dans le Dao pour récupérer la liste des pays mais je ne sais pas comment l'afficher dans un checkbox.

// Entité et Dao
public class Pays  implements Serializable {
 private int idPays;
 private String pays_code;
 private String pays_indicatif;
 private String pays_nom;
 
 private Collection<Client> clients;
 
 private Collection<Facturier> facturiers;
 
 
 
 public Pays(int idPays){
  super();
  this.idPays=idPays;
 }

  public Pays(int idPays, String pays_nom) {
  super();
  this.idPays = idPays;
  this.pays_nom = pays_nom;
 }

public Pays() {
   super();
  }
 public Pays(int idPays, String pays_code, String pays_indicatif, String pays_nom) {
  super();
  this.idPays = idPays;
  this.pays_code = pays_code;
  this.pays_indicatif = pays_indicatif;
  this.pays_nom = pays_nom;
 }


 public int getIdPays() {
  return idPays;
 }


 public void setIdPays(int idPays) {
  this.idPays = idPays;
 }


 public String getPays_code() {
  return pays_code;
 }


 public void setPays_code(String pays_code) {
  this.pays_code = pays_code;
 }


 public String getPays_indicatif() {
  return pays_indicatif;
 }


 public void setPays_indicatif(String pays_indicatif) {
  this.pays_indicatif = pays_indicatif;
 }


 public String getPays_nom() {
  return pays_nom;
 }


 public void setPays_nom(String pays_nom) {
  this.pays_nom = pays_nom;
 }
 
 
}

package sn.mobilebanking.domaine;

import java.io.Serializable;
import java.util.Collection;

public class Client implements Serializable{
 private int idclients;
 private String clients_name;
 private String clients_email;
 private String clients_numero;
 private String clients_password;
 private String clients_solde;
 private String clients_etat_compte;
 private Pays pays;//Clé étrangère
 private int pays_idpays;
 //Un client a plusieurs facturiers
 private Collection<Facturier> facturiers;
 
 public Client() {
  super();
  // TODO Auto-generated constructor stub
 }

 public int getPays_idpays() {
  return pays_idpays;
 }

 public void setPays_idpays(int pays_idpays) {
  this.pays_idpays = pays_idpays;
 }

 public Client(String clients_name) {
  super();
  this.clients_name = clients_name;
 }

 public Client(int idclients, String clients_name, String clients_email, String clients_numero,
   String clients_password, String clients_solde, String clients_etat_compte, int pays_idpays) {
  super();
  this.idclients = idclients;
  this.clients_name = clients_name;
  this.clients_email = clients_email;
  this.clients_numero = clients_numero;
  this.clients_password = clients_password;
  this.clients_solde = clients_solde;
  this.clients_etat_compte = clients_etat_compte;
  this.pays_idpays = pays_idpays;
 }

 public Client(int idclients, String clients_name, String clients_email, String clients_numero,
   String clients_password, String clients_solde, String clients_etat_compte, Pays pays) {
  super();
  this.idclients = idclients;
  this.clients_name = clients_name;
  this.clients_email = clients_email;
  this.clients_numero = clients_numero;
  this.clients_password = clients_password;
  this.clients_solde = clients_solde;
  this.clients_etat_compte = clients_etat_compte;
  this.pays = pays;
 }

 public Client(int idclients, String clients_name, String clients_email, String clients_numero,
   String clients_password, String clients_solde, String clients_etat_compte, Pays pays,
   Collection<Facturier> facturiers) {
  super();
  this.idclients = idclients;
  this.clients_name = clients_name;
  this.clients_email = clients_email;
  this.clients_numero = clients_numero;
  this.clients_password = clients_password;
  this.clients_solde = clients_solde;
  this.clients_etat_compte = clients_etat_compte;
  this.pays = pays;
  this.facturiers = facturiers;
 }

 public int getIdclients() {
  return idclients;
 }

 public void setIdclients(int idclients) {
  this.idclients = idclients;
 }

 public String getClients_name() {
  return clients_name;
 }

 public void setClients_name(String clients_name) {
  this.clients_name = clients_name;
 }

 public String getClients_email() {
  return clients_email;
 }

 public void setClients_email(String clients_email) {
  this.clients_email = clients_email;
 }

 public String getClients_numero() {
  return clients_numero;
 }

 public void setClients_numero(String clients_numero) {
  this.clients_numero = clients_numero;
 }

 public String getClients_password() {
  return clients_password;
 }

 public void setClients_password(String clients_password) {
  this.clients_password = clients_password;
 }

 public String getClients_solde() {
  return clients_solde;
 }

 public void setClients_solde(String clients_solde) {
  this.clients_solde = clients_solde;
 }

 public String getClients_etat_compte() {
  return clients_etat_compte;
 }

 public void setClients_etat_compte(String clients_etat_compte) {
  this.clients_etat_compte = clients_etat_compte;
 }

 public Pays getPays() {
  return pays;
 }

 public void setPays(Pays pays) {
  this.pays = pays;
 }

 public Collection<Facturier> getFacturiers() {
  return facturiers;
 }

 public void setFacturiers(Collection<Facturier> facturiers) {
  this.facturiers = facturiers;
 }
 
 
}

 @Override
 public void ajouterClient(Client client) {
  // Gestion de la sécurité du mot de passe
  SecurityMechanism sm = new SecurityMechanism();
  
  // Préparation de la requête
  String sql = "INSERT INTO clients(clients_name,clients_email,clients_numero,clients_password,clients_solde,clients_etat_compte,pays_idpays) VALUES (?,?,?,?,?,?,?)";

  try {
   // Création d'une zone de requête
   PreparedStatement pst = conn.prepareStatement(sql);
   // Transmission des valeurs aux paramètres de la requête
   pst.setString(1, client.getClients_name());
   pst.setString(2, client.getClients_email());
   pst.setString(3, client.getClients_numero());
   pst.setString(4, sm.getEncrypted(client.getClients_password()));
   pst.setString(5, client.getClients_solde());
   pst.setString(6, client.getClients_etat_compte());
   pst.setInt(7, client.getPays().getIdPays());
   

   // Execution de la requete

   pst.executeUpdate();
   System.out.println("Insertion du client réussie avec succès !!!!");

  } catch (SQLException e) {
   System.out.println("Problème de requête !!!!");
   e.printStackTrace();
  }

 }
@Override
 public List<Pays> listerPays() {
  List<Pays> list = new ArrayList<>();
  Pays py = null;

  try {
   // Préparation de la requête
   String sql = "SELECT pays_nom FROM pays";

   // Création d'une zone de requête
   Statement st = conn.createStatement();

   // Exécution de la requpete
   ResultSet rs = st.executeQuery(sql);

   // Traitement du resultat de la requête
   while (rs.next()) {
    int id_pays = Integer.parseInt(rs.getString("idpays"));
    String nom_pays=rs.getString("pays_nom");
       py=new Pays(id_pays, nom_pays);   
    list.add(py);
    System.out.println("Liste retrouvée avec succès !!!!");
   }
  } catch (SQLException e) {
   System.out.println("Problème de requête !!!!");
   e.printStackTrace();
  }
  return list;
 }
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015 > Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
18 juil. 2018 à 21:41
Ta méthode listerPays() pourrait suffire, même si elle est boguée à cause du getString("idpays").

<select>
<c:forEach var="pays" items="${listePays}" >
    <option value="${pays.idpays}">${pays.pays_nom}</option>
</c:forEach>
</select>

Remarque : normalement un nom Java ne devrait jamais contenir de
_
(sauf pour les constantes).
De plus il n'est pas nécessaire de rappeler dans chaque méthode le nom de la classe, si tu fais
pays.getId()
ou
pays.getNom()
ça suffit, pas besoin de faire
pays.getPaysId()
ou
pays.getPaysNom()
, on sait que c'est un pays.
0
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
Modifié le 19 juil. 2018 à 10:38
Merci beaucoup KX pour tout.J'ai pu l'afficher finalement.Mais pour insérer un client dans la base de données j'ai cette erreur j'ai cherché en vain mais pas d'issue.Ci-dessous:

Problème de requête !!!!
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`owo`.`clients`, CONSTRAINT `fk_clients_pays1` FOREIGN KEY (`pays_idpays`) REFERENCES `pays` (`idpays`) ON DELETE NO ACTION ON UPDATE NO ACTION)
 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
 at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
 at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169)
 at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:693)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303)
 at sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:179)
 at sn.mobilebanking.service.ServiceClientImpl.addClient(ServiceClientImpl.java:29)
 at sn.mobilebanking.presentation.CheckRegisterAllClientControleur.doPost(CheckRegisterAllClientControleur.java:57)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
 at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
 at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
 at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Unknown Source)

//////Méthode d'ajout du client
 @Override
 public void ajouterClient(Client client) {
  // Gestion de la sécurité du mot de passe
  SecurityMechanism sm = new SecurityMechanism();
  
  // Préparation de la requête
  String sql = "INSERT INTO clients(clients_name,clients_email,clients_numero,clients_password,clients_solde,clients_etat_compte,pays_idpays) VALUES (?,?,?,?,?,?,?)";

  try {
   // Création d'une zone de requête
   PreparedStatement pst = conn.prepareStatement(sql);
   // Transmission des valeurs aux paramètres de la requête
   pst.setString(1, client.getClients_name());
   pst.setString(2, client.getClients_email());
   pst.setString(3, client.getClients_numero());
   pst.setString(4, sm.getEncrypted(client.getClients_password()));
   pst.setString(5, client.getClients_solde());
   pst.setString(6, client.getClients_etat_compte());
   pst.setInt(7, client.getPays_idpays());
   

   // Execution de la requete

   pst.executeUpdate();
   System.out.println("Insertion du client réussie avec succès !!!!");

  } catch (SQLException e) {
   System.out.println("Problème de requête !!!!");
   e.printStackTrace();
  }

 }



////////Sql

-- -----------------------------------------------------
-- Table `OWO`.`pays`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `OWO`.`pays` (
  `idpays` INT NOT NULL AUTO_INCREMENT,
  `pays_code` INT NOT NULL,
  `pays_indicatif` INT NOT NULL,
  `pays_nom` VARCHAR(45) NULL,
  PRIMARY KEY (`idpays`),
  UNIQUE INDEX `pays_code_UNIQUE` (`pays_code` ASC),
  UNIQUE INDEX `pays_indicatif_UNIQUE` (`pays_indicatif` ASC))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `OWO`.`clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `OWO`.`clients` (
  `idclients` INT NOT NULL AUTO_INCREMENT,
  `clients_name` VARCHAR(45) NOT NULL,
  `clients_email` VARCHAR(45) NOT NULL,
  `clients_numero` VARCHAR(45) NOT NULL,
  `clients_password` VARCHAR(45) NULL,
  `clients_solde` VARCHAR(45) NULL,
  `clients_etat_compte` VARCHAR(45) NULL,
  `pays_idpays` INT NOT NULL,
  PRIMARY KEY (`idclients`),
  UNIQUE INDEX `clients_email_UNIQUE` (`clients_email` ASC),
  UNIQUE INDEX `clients_numero_UNIQUE` (`clients_numero` ASC),
  INDEX `fk_clients_pays1_idx` (`pays_idpays` ASC),
  CONSTRAINT `fk_clients_pays1`
    FOREIGN KEY (`pays_idpays`)
    REFERENCES `OWO`.`pays` (`idpays`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015
19 juil. 2018 à 11:22
Là c'est un pur problème de SQL, tu ferais la même requête dans un éditeur SQL tu aurais la même erreur, Java ne fait que la récupérer et la transformer en exception.

Dans ta table clients tu imposes qu'un client doit toujours avoir un idpays qui existe déjà dans la table pays.

  CONSTRAINT `fk_clients_pays1`
    FOREIGN KEY (`pays_idpays`)
    REFERENCES `OWO`.`pays` (`idpays`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

C'est cette contrainte que tu n'as pas respecté, en ajoutant un client avec un idpays qui n'existe pas.

Remarque : il faut fermer tes ressources, un PreparedStatement ça s'ouvre mais ça doit se fermer aussi, y compris en cas d'exception. Le plus sécurisé étant de passer par un try-with-ressources.

Ne pas hésiter non plus à propager tes exceptions. Actuellement tu les masques et tu continues comme si ça avait fonctionné, mais il serait pertinent que cette erreur remonte, pour pouvoir indiquer au reste du programme qu'il y a eu un problème à l'ajout, sinon on va continuer à manipuler un client qui n'existe pas, de même qu'on essaye de l'ajouter à un pays qui n'existe pas (une autre erreur ignorée précédemment ?)

Exemple :

@Override
public void ajouterClient(Client client) throws ProjectException {
    SecurityMechanism sm = new SecurityMechanism();
    String sql = "INSERT INTO clients (clients_name, clients_email, clients_numero, clients_password, clients_solde, clients_etat_compte, pays_idpays) VALUES (?, ?, ?, ?, ?, ?, ?)";
    try (PreparedStatement pst = conn.prepareStatement(sql)) {
        pst.setString(1, client.getClients_name());
        pst.setString(2, client.getClients_email());
        pst.setString(3, client.getClients_numero());
        pst.setString(4, sm.getEncrypted(client.getClients_password()));
        pst.setString(5, client.getClients_solde());
        pst.setString(6, client.getClients_etat_compte());
        pst.setInt(7, client.getPays_idpays());

        int result = pst.executeUpdate();
        if (result != 1) {
            throw new IllegalStateException("executeUpdate a retourné " + result);
        }
    } catch (SQLException | RuntimeException e) {
        throw new ProjectException("Le client n'a pas pu être ajouté : " + client, e);
    }
}

Remarque : pour que l'information soit utile, il faut que la méthode toString() de la classe Client contienne tous les attributs du client qui sont utilisés (sauf le password bien sûr, qui doit être caché).

Avec par exemple un exception personnalisée comme celle-ci :

public class ProjectException extends Exception {
    private static final long serialVersionUID = 1;

    public ProjectException(String message) {
        super(message);
    }

    public ProjectException(String message, Throwable cause) {
        super(message, cause);
    }

    public ProjectException(Throwable cause) {
        super(cause);
    }
}
0
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
Modifié le 19 juil. 2018 à 15:21
Bonjour KX j'ai cherché en vain.

Je n'ai pas bien compris votre explication:
CONSTRAINT `fk_clients_pays1`
    FOREIGN KEY (`pays_idpays`)
    REFERENCES `OWO`.`pays` (`idpays`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

Au fait les pays sont déjà enrégistrées dans la base de données avec leur id qui est autoincrémenté.Et puis quand je procède à l'insertion des clients au niveau de WampServeur ça passe normalement.Le problème c'est quand je le fais à partir du code java.
J'ai essayé avec vos remarques précédentes mais l'erreur y est toujours:
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`owo`.`clients`, CONSTRAINT `fk_clients_pays1` FOREIGN KEY (`pays_idpays`) REFERENCES `pays` (`idpays`) ON DELETE NO ACTION ON UPDATE NO ACTION)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1169)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:693)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1404)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1318)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1303)
at sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:203)
... 23 more



Quand j'essaie de passer par la table pays afin de récupérer son id c'est à dire la dernière ligne de la table client comme ci-dessous j'ai cette erreur:

@Override
public void ajouterClient(Client client) throws ProjectException {
    SecurityMechanism sm = new SecurityMechanism();
    String sql = "INSERT INTO clients (clients_name, clients_email, clients_numero, clients_password, clients_solde, clients_etat_compte, pays_idpays) VALUES (?, ?, ?, ?, ?, ?, ?)";
    try (PreparedStatement pst = conn.prepareStatement(sql)) {
        pst.setString(1, client.getClients_name());
        pst.setString(2, client.getClients_email());
        pst.setString(3, client.getClients_numero());
        pst.setString(4, sm.getEncrypted(client.getClients_password()));
        pst.setString(5, client.getClients_solde());
        pst.setString(6, client.getClients_etat_compte());
       // pst.setInt(7, client.getPays_idpays());
          pst.setInt(7, client.getPays().getIdpays());

        int result = pst.executeUpdate();
        if (result != 1) {
            throw new IllegalStateException("executeUpdate a retourné " + result);
        }
    } catch (SQLException | RuntimeException e) {
        throw new ProjectException("Le client n'a pas pu être ajouté : " + client, e);
    }
}

sn.mobilebanking.domaine.ProjectException: Le client n'a pas pu être ajouté : sn.mobilebanking.domaine.Client@50fbd774
at sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:208)
at sn.mobilebanking.service.ServiceClientImpl.addClient(ServiceClientImpl.java:30)
at sn.mobilebanking.presentation.CheckRegisterAllClientControleur.doPost(CheckRegisterAllClientControleur.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)



Je ne sais plus quoi faire.Ici c'est la table Client
public class Client implements Serializable{
 private int idclients;
 private String clients_name;
 private String clients_email;
 private String clients_numero;
 private String clients_password;
 private String clients_solde;
 private String clients_etat_compte;
 private Pays pays;//Clé étrangère
////Controleur
@WebServlet("/chargerAjoutClient")
public class  ChargementAjoutClientControleur extends HttpServlet {
 private static final long serialVersionUID = 1L;
    public static final String ATT_FORM = "form";

 public ChargementAjoutClientControleur() {
  super();
 }
 
 /**


* @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());

  ServiceClientImpl serv=new ServiceClientImpl();
  List<Pays> listePays=serv.listerPays();//Lister les noms des pays
    request.setAttribute("listePays", listePays);
       //Redirection vers la liste des modérateurs
      request.getRequestDispatcher("client/ajouterClient.jsp").forward(request, response);
  
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
//   }
 }
}


//Vue
<label>Selectionner le pays</label> <select
           class="form-control" name="nomPays">
               <c:forEach var="pays" items="${listePays }">
               <option value="${pays.idpays }">${pays.idpays }- ${pays.pays_nom }</option>
               </c:forEach>
          </select>
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015 > Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
19 juil. 2018 à 15:33
"ProjectException: Le client n'a pas pu être ajouté : sn.mobilebanking.domaine.Client@50fbd774"
Comme je le mettais dans ma remarque, pour que cette information soit utile, il faut que la méthode toString() de la classe Client contienne tous les attributs du client qui sont utilisés.
En particulier ce que l'on veut quand l'exception l'affiche c'est savoir que est l'id du pays qui a été mis dans la requête, puisque c'est un id qui n'existe pas il faut savoir quelle est sa valeur et comprendre d'où elle vient.

Pour faire le toString de la classe Client, tu peux le faire à la main ou en utilisant ton IDE.
Par exemple sur Eclipse, tu fais un clic droit dans le code de la classe Client, tu sélectionnes le menu "Source" et le sous-menu "Generate toString()"
0
Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
Modifié le 19 juil. 2018 à 17:29
Hello KX,voici la méthode toString()
@Override
 public String toString() {
  return "Client [idclients=" + idclients + ", clients_name=" + clients_name + ", clients_email=" + clients_email
    + ", clients_numero=" + clients_numero + ", clients_password=" + clients_password + ", clients_solde="
    + clients_solde + ", clients_etat_compte=" + clients_etat_compte + ", pays=" + pays + "]";
 }




Mais dans le résultat les champs password et pays sont restés nulls.

sn.mobilebanking.domaine.ProjectException: Le client n'a pas pu être ajouté : Client [idclients=0, clients_name=zozor, clients_email=zozor@gmail.com, clients_numero=12, clients_password=null, clients_solde=12000, clients_etat_compte=OK, pays=null]
at sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:209)
at sn.mobilebanking.service.ServiceClientImpl.addClient(ServiceClientImpl.java:30)
at sn.mobilebanking.presentation.CheckRegisterAllClientControleur.doPost(CheckRegisterAllClientControleur.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:203)
... 23 more



Je ne sais pas ce qui ne va pas.Est ce que le problème vient d'ici?

         pst.setString(4, sm.getEncrypted(client.getClients_password()));
                pst.setInt(7, client.getPays().getIdpays());
0
KX Messages postés 16733 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 31 janvier 2024 3 015 > Streamooc Messages postés 79 Date d'inscription samedi 17 juin 2017 Statut Membre Dernière intervention 8 février 2023
Modifié le 19 juil. 2018 à 17:43
Il faut regarder où est la ligne 203 dans DaoClientImpl.java mais effectivement, si pays=null, le client.getPays() va faire un NullPointerException.

Remarque : ce n'est pas la même erreur qu'avant, puisque tu avais une SQLException au moment où tu faisais la requête, et que maintenant le programme plante avant même d'avoir fait la requête...

Ceci étant dit on avance quand même un peu, car maintenant tu as le détail du client, tu as pu facilement identifier qu'il y avait un problème sur le pays (mais ça on s'en doutait déjà un peu), mais également un problème sur le password alors que jusqu'à présent on n'en savait rien.

Mais pour corriger le problème il va falloir regarder le code d'avant, au moment où tu construis l'objet Client et que tu fais tes setPays et setPassword (si tu les as fait) pour comprendre pourquoi ces valeurs sont null.

Il va donc falloir s'intéresser aux différentes méthodes mentionnées dans la stackTrace, ce sont elles qui ont conduit à l'erreur :
  • sn.mobilebanking.dao.DaoClientImpl.ajouterClient(DaoClientImpl.java:203)
  • sn.mobilebanking.service.ServiceClientImpl.addClient(ServiceClientImpl.java:30)
  • sn.mobilebanking.presentation.CheckRegisterAllClientControleur.doPost(CheckRegisterAllClientControleur.java:59)
0