IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Servlets/JSP Java Discussion :

Probleme d'affichage image blob provenant d'une base de données dans une page JSP


Sujet :

Servlets/JSP Java

  1. #1
    Membre régulier
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2012
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Congo-Kinshasa

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Enseignement

    Informations forums :
    Inscription : Octobre 2012
    Messages : 100
    Points : 91
    Points
    91
    Par défaut Probleme d'affichage image blob provenant d'une base de données dans une page JSP
    Je suis en trein de réaliser une applications sous J2EE en utilisant le JSP et Servlet pour la vente des produits.
    L'application arrive bien à enregistrer les informations du produit ainsi que sa photo dans la base de données. La photo est du type blob dans mysql, mais lorsque je veux afficher la liste des produits, l'image de la photo ne s'affiche pas et je ne sais pas ou se trouve mon erreur.

    Voici comment se présente les codes sources:

    1. StockArticle.jsp

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Gestion des articles</title>
    </head>
    <body>
    <center>
        <form name="form" method="post" action="stockArticle" enctype="multipart/form-data">
            <table border=0>
                <tr>
                    <td>Id produit</td>
                    <td><input type="text" size="30" name="idproduit" required/></td>
                </tr>
     
                <tr>
                    <td>Désignation</td>
                    <td><input type="text" size="30" name="nomproduit" required/></td>
                </tr>
     
                <tr>
                    <td>Categorie</td>
                    <td>
                    <select name="categorie">
                    <option value="parfumerie">Parfumerie</option>
                    <option value="charcuterie">Charcutérie</option>
                    <option value="vin">Vin</option>                
                    </select>
                    </td>
                </tr>
     
                <tr>
                    <td>Prix</td>
                    <td><input type="text" size="30" name="prix" required/></td>
                </tr>
     
                <tr>
                    <td>Photo: </td>
                    <td><input type="file" name="photo" size="50"/></td>
                </tr>
     
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save"/>
                    </td>
                </tr>
            </table>
        </form>
     
        <table  border="1" width="80%">
         <tr>
             <th width="5%">ID</th><th width="20%">NOM</th><th width="15%">CATEGORIE</th>
             <th width="20%">PRIX</th><th width="15%">PHOTO</th>
              <th>SUPPRIMER</th><th>MODIFIER</th>
         </tr>
         <!-- modele.nom_Classe_metier qui contient les données -->
     
         <c:forEach items="${modele.produit }" var="p">
         <tr>
           <td>${p.idproduit}</td>
           <td>${p.nomproduit}</td>
           <td>${p.categorie}</td>
           <td>${p.prix}</td>
           <td>
              <img src='"+"DisplayPicture?imageid="+${p.idproduit}+"'" width="65px" height="30px">
            </td>
     
     
     
            <td><center><a href="deleteProduit.php?id=${p.idproduit}&action=supprimer">OK</a></center></td>
            <td><center><a href="deleteProduit.php?id=${p.idproduit}&action=modifier">OK</a></center></td>
           </tr>
         </c:forEach>
     </table>
     
    </center>
     
    </body>
    </html>
    2.
    2.1.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    package web;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
     
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
     
    import metier.IStockArticle;
    import metier.IStockArticleImpl;
    import metier.Produit;
    import metier.StockArticle;
     
    /**
     * Servlet implementation class StockArticleServlet
     */
     
    //ceci est obligatoire pour télécharger la photo
    @MultipartConfig(maxFileSize = 16177215)// upload file's size up to 16MB
     
    public class StockArticleServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
     
        //crearion d'un objet Interface qui doit initialiser plutard 
        //être crée et initialiser par la classe implémentation
        private IStockArticle metier;
     
        @Override
        public void init() throws ServletException {
            metier=new IStockArticleImpl();
        }
     
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
            //récupérarion des donnée
            String idproduit=request.getParameter("idproduit");
            String nomproduit=request.getParameter("nomproduit");
            String cat=request.getParameter("categorie");
            double prix=Double.parseDouble(request.getParameter("prix"));
            String nomphoto=null;
            String cheminPhoto=request.getParameter("photo");
            System.out.println("idproduit:"+idproduit+" nom:"+nomproduit+" cat:"+cat+" prix:"+prix);
            // input stream of the upload file
            InputStream inputStream = null; 
     
            // obtains the upload file part in this multipart request
            Part filePart = request.getPart("photo");
            System.out.println("chemin photo:"+cheminPhoto);
     
            // System.out.println("photo chemin:"+filePart);
            if (filePart != null) {
                 // prints out some information for debugging
                   System.out.println("file name:"+filePart.getName());
                   System.out.println("file taille:"+filePart.getSize());
                   System.out.println("file type:"+filePart.getContentType());
                   //initialisation du nom photo
                   nomphoto=filePart.getName();
                   // obtains input stream of the upload file
                   inputStream = filePart.getInputStream();
            }
     
            //creation d'un objet de la classe implémentation
              //qui nous donnera accès à toutes les méthodes
              IStockArticleImpl metier=new IStockArticleImpl();
              //déclaration d'un objet article
              StockArticle s;
            //test si le flux d'image existe(inputStream != null)
            if (filePart.getSize() !=0) {
               //creation d'un objet
                 s=new StockArticle(idproduit,nomproduit,cat,prix,nomphoto,inputStream);            
            }else{
                s=new StockArticle(idproduit,nomproduit,cat,prix);            
            }//fin if
     
            //ajoutons un nouveau produit
            metier.ajouterProduit(s);
     
            //creer un objet du type modele
            StockArticleModele mod=new StockArticleModele();
     
            //on fait appel à la couche métier pour donnée la liste des produits
            ArrayList<StockArticle>article=metier.getAllStock();
            //fixons les resultats dans le modele grace au setter de la 
            //collection StockArticle  
            mod.setProduit(article);
     
            //pour afficher les contenues du modele, on doit faire 
            //une redirection vers la page JSP(cette page cherchera a connaitre quel modele a utilisé)
            request.setAttribute("modele",mod);
            request.getRequestDispatcher("StockArticle.jsp").forward(request,response);
     
     
        }//doPost
     
    }
    2.2.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    package web;
     
    import java.io.*;
    import java.net.*;
    import java.sql.*;
     
    import javax.naming.InitialContext;
    import javax.servlet.*;
    import javax.servlet.http.*;
     
     
    public class DisplayPicture extends HttpServlet {
        private static final long serialVersionUID = 1L;
     
          /** Creates a new instance of DisplayPicture */
        public DisplayPicture() {
        }
     
     
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
     
        }
     
        public void destroy() {
        }
     
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     
     
            String id=request.getParameter("imageid");
            String ct=request.getParameter("contenttype");
            if ((ct==null)||(ct.equals(""))) {
                ct="image/x-jpeg";
            }
            System.out.println("Now displaying image with ID: "+id);
     
            try {
                ServletOutputStream out = response.getOutputStream();
                response.setContentType(ct);
                out.write(this.getImage(id));
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
     
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        }
     
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        }
     
        /** Returns a short description of the servlet.
         */
        public String getServletInfo() {
            return "Displays a picture from the database identified by a parameter IMAGEID";
        }
     
        private byte[] getImage(String id) {
            Statement sta=null;
            Connection con=null;
            ResultSet rs=null;
            byte[] result=null;
     
            try {
                //Context initCtx = new InitialContext();
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/appdb","root","");
     
                sta = con.createStatement();
                rs=sta.executeQuery("SELECT photo FROM produit WHERE idproduit='"+id+"'");
                if (rs.next()) {
                    result=rs.getBytes("photo");
                } else {
                    System.out.println("Could find image with the ID specified or there is a problem with the database connection");
                }
                rs.close();
                sta.close();
                con.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
            return result;
        }
    }
    3.
    3.1.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    package metier;
     
    import java.io.InputStream;
    import java.io.Serializable;
     
    public class StockArticle implements Serializable{
     
        //Délcaration des attributs
        private String idproduit;
        private String nomproduit;
        private String categorie;
        private double prix;
        private byte[] photo;
        private String nomphoto;
     
        private InputStream is;
     
        //Getters et setters
     
        public String getIdproduit() {
            return idproduit;
        }
        public void setIdproduit(String idproduit) {
            this.idproduit = idproduit;
        }
        public String getNomproduit() {
            return nomproduit;
        }
        public void setNomproduit(String nomproduit) {
            this.nomproduit = nomproduit;
        }
        public String getCategorie() {
            return categorie;
        }
        public void setCategorie(String categorie) {
            this.categorie = categorie;
        }
        public double getPrix() {
            return prix;
        }
        public void setPrix(double prix) {
            this.prix = prix;
        }
        public byte[] getPhoto() {
            return photo;
        }
        public void setPhoto(byte[] photo) {
            this.photo = photo;
        }
        public String getNomphoto() {
            return nomphoto;
        }
        public void setNomphoto(String nomphoto) {
            this.nomphoto = nomphoto;
        }
     
     
        public InputStream getIs() {
            return is;
        }
        public void setIs(InputStream is) {
            this.is = is;
        }
     
        //1. constructeur vide
        public StockArticle() {
            super();
        }
     
        //constructeur pour la création d'un nouveau article avec photo
     
        //Constructeur avec flux d'image
        public StockArticle(String idproduit, String nomproduit, String categorie,
                double prix, String nomphoto, InputStream is) {
            super();
            this.idproduit = idproduit;
            this.nomproduit = nomproduit;
            this.categorie = categorie;
            this.prix = prix;
            this.nomphoto = nomphoto;
            this.is = is;
        }    
     
        //constructeur sans photo
        public StockArticle(String idproduit, String nomproduit, String categorie,
                double prix) {
            super();
            this.idproduit = idproduit;
            this.nomproduit = nomproduit;
            this.categorie = categorie;
            this.prix = prix;
     
        }
     
     
        //contructeur pour la recherche produit
        public StockArticle(String idproduit) {
            super();
            this.idproduit = idproduit;
        }
     
     
    }
    3.2.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package metier;
     
    import java.util.ArrayList;
     
    //La classe interface contient uniquement les nom des méthodes
    //provenant de la classe métier StockArticle
     
    public interface IStockArticle {
     
        public void ajouterProduit(StockArticle s);
        public void modifierProduit(StockArticle s);
        public void supprimerProduit(String idproduit);
        public ArrayList<StockArticle> getAllStock();
        public ArrayList<StockArticle> getStockArticle(String idproduit);
        public ArrayList<StockArticle> getStockArticleMC(String mc);
     
     
    }
    3.3.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    package metier;
     
    import java.io.ByteArrayInputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
     
    import org.apache.tomcat.util.http.fileupload.IOUtils;
     
    /*Une classe implémentation decrire toutes les méthodes
     * d'une classe Interface à partenant dans le même 
     * package métier. Dans notre cas, on doit réaliser la classe
     * implémentation de l'interface IStockArticle
     * 
     * */
     
    public class IStockArticleImpl implements IStockArticle{
     
     
        @Override
        public void ajouterProduit(StockArticle s) {
     
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/appdb","root","");
     
                PreparedStatement pstmt=null;
                String requette;
     
                //la requette a exécuter varie selon que l'article a une photo ou pas
                //dans c'est cas on doit tester le champs photo
     
                if(s.getIs()!=null){
                    requette="insert into produit(idproduit,nomproduit,categorie,prix,photo,nomphoto)"
                            + "values(?,?,?,?,?,?)";
                    pstmt=c.prepareStatement(requette);
                    pstmt.setString(1, s.getIdproduit());
                    pstmt.setString(2, s.getNomproduit());
                    pstmt.setString(3, s.getCategorie());
                    pstmt.setDouble(4, s.getPrix());
                    // fetches input stream of the upload file for the blob column
                    pstmt.setBlob(5, s.getIs());
                    pstmt.setString(6, s.getNomphoto());
     
                }else{
                    requette="insert into produit(idproduit,nomproduit,categorie,prix)"
                            + "values(?,?,?,?)";
                    pstmt=c.prepareStatement(requette);
                    pstmt.setString(1, s.getIdproduit());
                    pstmt.setString(2, s.getNomproduit());
                    pstmt.setString(3, s.getCategorie());
                    pstmt.setDouble(4, s.getPrix());
     
                }//fin if
     
                //exécution de la requette
                pstmt.execute();
                System.out.println("Produit ajoute dans le stock");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
     
        }
     
        @Override
        public void modifierProduit(StockArticle s) {
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public void supprimerProduit(String idproduit) {
            // TODO Auto-generated method stub
     
        }
     
        @Override
        public ArrayList<StockArticle> getAllStock() {
            ArrayList<StockArticle>article=new ArrayList();
     
            try {
                Class.forName("com.mysql.jdbc.Driver");            
                Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/appdb","root","");
     
                String requette="select * from produit";
                PreparedStatement pstmt=c.prepareStatement(requette);
                ResultSet rs=pstmt.executeQuery();
     
                while(rs.next()){
                    StockArticle s=new StockArticle();
                    s.setIdproduit(rs.getString("idproduit"));
                    s.setNomproduit(rs.getString("nomproduit"));
                    s.setCategorie(rs.getString("categorie"));
                    s.setPrix(rs.getInt("prix"));
                    s.setPhoto(rs.getBytes("photo"));
                    s.setNomphoto(rs.getString("nomphoto"));
     
                    article.add(s);
                }//while
     
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
     
            return article;
        }
     
        @Override
        public ArrayList<StockArticle> getStockArticle(String idproduit) {
            ArrayList<StockArticle>article=new ArrayList();
     
            try {
                Class.forName("com.mysql.jdbc.Driver");            
                Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/appdb","root","");
     
                String requette="select * from produit where idproduit=?";
                PreparedStatement pstmt=c.prepareStatement(requette);
                pstmt.setString(1,idproduit);
                ResultSet rs=pstmt.executeQuery();
     
                if(rs.next()){
                    StockArticle s=new StockArticle();
                    s.setIdproduit(rs.getString("idproduit"));
                    s.setNomproduit("nomproduit");
                    s.setCategorie(rs.getString("categorie"));
                    s.setPhoto(rs.getBytes("photo"));
                    s.setNomphoto(rs.getString("nomphoto"));                
                    article.add(s);
                }//while
     
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
     
            return article;
        }
     
        @Override
        public ArrayList<StockArticle> getStockArticleMC(String mc) {
            // TODO Auto-generated method stub
            return null;
        }
     
     
    }
    Svp, aidez moi.

  2. #2
    Rédacteur/Modérateur
    Avatar de Logan Mauzaize
    Homme Profil pro
    Architecte technique
    Inscrit en
    Août 2005
    Messages
    2 894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Architecte technique
    Secteur : Transports

    Informations forums :
    Inscription : Août 2005
    Messages : 2 894
    Points : 7 083
    Points
    7 083
    Par défaut
    As-tu commencé par tester si ton URL renvoie bien une image dans ton navigateur ?

    Tu peux également vérifier dans le panneau "débuggage" de ton navigateur (généralement accessible via la touche "F12"). Tu as généralement un onglet "Réseau" ou "Network" qui te permet de contrôler le chargement des ressources.
    Java : Cours et tutoriels - FAQ - Java SE 8 API - Programmation concurrente
    Ceylon : Installation - Concepts de base - Typage - Appels et arguments

    ECM = Exemple(reproduit le problème) Complet (code compilable) Minimal (ne postez pas votre application !)
    Une solution vous convient ? N'oubliez pas le tag
    Signature par pitipoisson

Discussions similaires

  1. [MySQL] Remplacer une chaîne de caractères dans une base de données
    Par Furius dans le forum PHP & Base de données
    Réponses: 10
    Dernier message: 27/11/2013, 21h06
  2. [MySQL] Affichage des données d'une base de données dans un tableau
    Par valmeras dans le forum PHP & Base de données
    Réponses: 0
    Dernier message: 02/02/2012, 20h14
  3. inserer les données d'une base de données dans une autres?
    Par enstein8 dans le forum MS SQL Server
    Réponses: 8
    Dernier message: 14/10/2011, 13h33
  4. Affichage des données d'une base de données dans un formpanel
    Par DiverSIG dans le forum Ext JS / Sencha
    Réponses: 2
    Dernier message: 28/09/2011, 23h01
  5. Réponses: 2
    Dernier message: 18/03/2007, 19h02

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo