Link to home
Start Free TrialLog in
Avatar of Mimi1979
Mimi1979

asked on

Dabase connection in servlet

Sharing the Database connection with different servlets
Avatar of Mimi1979
Mimi1979

ASKER

I have three servlets and they are ran from a HTML web page
Servlet1 -->

public class Categorie_servlet extends HttpServlet {
    private static final String CONTENT_TYPE =
        "text/html; charset=windows-1252";

    private Connection connexion = null;
    private String URL = "jdbc:odbc:inventaire";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            connexion = DriverManager.getConnection(URL, "", "mp");
        } catch (Exception e) {
            e.printStackTrace();
            connexion = null;
        }
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {

        PrintWriter sortie = response.getWriter();
        response.setContentType("text/html");
        Statement requete = null;
        ResultSet resultat = null;
        try {
            requete = connexion.createStatement();
            resultat = requete.executeQuery("SELECT no_categorie, nom_categorie FROM Categories");
        } catch (Exception e) {
            System.err.println("ERREUR: problème à la lecture de la selection");
            e.printStackTrace();

        }

        sortie.println("<HTML><HEAD><TITLE>");
        sortie.println("Toutes les categories de la BD Inventaire");
        sortie.println("</TITLE>");
        sortie.println("<link rel=stylesheet type=\"text/css\" href=\"style1.css\"></HEAD><BODY>");
        if (resultat != null) {
            // envoie la page HTML au client avec la table categories
            //sortie.println("<FORM name=\"form1\" action=\"afficherpiece\" method=\"POST\">");
            sortie.println("<FORM name=\"form1\" action=\"piecesparcategorie_servlet\" method=\"post\">");

            try {
                while (resultat.next()) {
                    String numCat = resultat.getString(1);
                    String nomCat = resultat.getString(2);
                    sortie.println("<H2>");
                    sortie.println("<input type=\"radio\" name=\"cate\" value=\"" +
                                   numCat + "\">" + nomCat + "<BR>");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            sortie.println(" <input type=\"submit\" name=\"soumission\" value=\"Soumettre\"><BR>");
            sortie.println("</H2>");
            sortie.println("</form>");
        } else
            sortie.print("<H2>Une erreur s'est produite. " +
                         "Veuillez réessayer plus tard.</H2>");

        sortie.println("</BODY></HTML>");
        sortie.close(); // clôturer le flux.
    }

    public void destroy() {
        try {
            connexion.close();
        } catch (Exception e) {
            System.err.println("Problème à la fermeture de" +
                               " la base de données");
        }
    }
}
**********************************************

Servlet 2 --->

package labo3_servlet_partageconnexion;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.*;
import javax.servlet.http.*;

public class PiecesParCategorie_servlet extends HttpServlet {
    private static final String CONTENT_TYPE =
        "text/html; charset=windows-1252";

    private Connection connexion = null;
    private String URL = "jdbc:odbc:inventaire";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            connexion = DriverManager.getConnection(URL, "", "mp");
        } catch (Exception e) {
            e.printStackTrace();
            connexion = null;
        }
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        PrintWriter sortie;
        String numCatChoisie = request.getParameter("cate");

        response.setContentType("text/html");
        sortie = response.getWriter();

        // envoie la page HTML au client avec la categorie chosie
        sortie.println("<HTML><HEAD><TITLE>");
        sortie.println("Table de la categorie choisie");
        sortie.println("</TITLE>");
        sortie.println("<link rel=stylesheet type=\"text/css\" href=\"style1.css\"></HEAD><BODY>");
        sortie.println("<p align=\"center\">Categorie choisie : " + numCatChoisie + "</P>");

        //Creation de l<objet pour la requete
        Statement stat = null;
       
        //Creating a ResulSet object
        ResultSet resultat = null;
        try {
            //Creating the connexion
            stat = connexion.createStatement();
           
            String requete1 = "SELECT Pieces.no_categorie, Pieces.description, Fabricants.nom_fabricant, " +
            "Pieces.prix_vente FROM Pieces, Fabricants " +
            "WHERE Pieces.no_fabricant=Fabricants.no_fabricant " +
            "AND Fabricants.nom_fabricant IN " +
            "(SELECT nom_fabricant FROM Fabricants " +
            "WHERE no_fabricant IN (SELECT no_fabricant FROM Pieces WHERE no_categorie='" + numCatChoisie+ "')) " +
            "AND Pieces.no_categorie='" + numCatChoisie+ "'";
            resultat = stat.executeQuery(requete1);
           
        } catch (Exception e) {
            System.err.println("ERREUR: problème à la lecture de la selection");
            e.printStackTrace();

        }

        // Reading the ResulSet object
        if (resultat != null) {
            sortie.println("<TABLE table cellspacing=\"3\" cellpadding=\"2\" border=\"1\" width=\"100%\">");
            sortie.println("<TR><TH><H2>" + "Numero de categorie" + "</H2></TH>");
            sortie.println("<TD><H2>" + "Description" + "</H2></TD>");
            sortie.println("<TD><H2>" + "Nom fabricant" + "</H2></TD>");
            sortie.println("<TD><H2>" + "Prix vente" + "</H2></TD></TR>");
            try {
                while (resultat.next()) {
                    //prender les valeurs de la premiere requete
                    String numCat = resultat.getString(1);
                    String des = resultat.getString(2);
                    String nomFab = resultat.getString(3);
                    String prix = resultat.getString(4);
                    sortie.println("<TR><TH>" + numCat + "</TH>");
                    sortie.println("<TD>" + des + "</TD>");
                    sortie.println("<TD>" + nomFab + "</TD>");
                    sortie.println("<TD>" + prix + "</TD></TR>");
                        }
                }
             catch (SQLException ex) {
                ex.printStackTrace();
            }
            sortie.println("</TABLE>");
        } else
            sortie.print("<H2>Une erreur s'est produite. " +
                         "Veuillez réessayer plus tard.</H2>");

        sortie.println("</BODY></HTML>");
        sortie.close(); // clôturer le flux.
    }

    public void destroy() {
        try {
            connexion.close();
        } catch (Exception e) {
            System.err.println("Problème à la fermeture de" +
                               " la base de données");
        }
    }
}

****************************************************

Servlet3--->

package labo3_servlet_partageconnexion;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.*;
import javax.servlet.http.*;

public class Pieces_servlet extends HttpServlet {
    private static final String CONTENT_TYPE =
        "text/html; charset=windows-1252";

    private Connection connexion = null;
    private String URL = "jdbc:odbc:inventaire";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            connexion = DriverManager.getConnection(URL, "", "mp");
        } catch (Exception e) {
            e.printStackTrace();
            connexion = null;
        }
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {

        PrintWriter sortie = response.getWriter();
        response.setContentType("text/html");
       
        // envoie la page HTML au client avec la categorie chosie
        sortie.println("<HTML><HEAD><TITLE>");
        sortie.println("</TITLE>");
        sortie.println("<link rel=stylesheet type=\"text/css\" href=\"style1.css\"></HEAD><BODY>");
        sortie.println("<p align=\"center\"> Listes de toutes les pieces </P>");
       
        Statement requete = null;
        ResultSet resultat = null;
        String query;

        // Initialisation de la connexion et executation de la requete
        try {
            requete = connexion.createStatement();
            query =
                    "SELECT Pieces.no_categorie, Pieces.description, Fabricants.nom_fabricant, " +
                    "Pieces.prix_vente FROM Pieces, Fabricants " +
                    "WHERE Pieces.no_fabricant=Fabricants.no_fabricant ";
            resultat = requete.executeQuery(query);
        } catch (Exception e) {
            System.err.println("ERREUR: problème à la lecture de la selection");
            e.printStackTrace();

        }

        // Reading the ResulSet object
        if (resultat != null) {
            sortie.println("<TABLE table cellspacing=\"3\" cellpadding=\"2\" border=\"1\" width=\"100%\">");
            sortie.println("<TR><TH><H2>" + "Numero de categorie" +
                           "</H2></TH>");
            sortie.println("<TD><H2>" + "Description" + "</H2></TD>");
            sortie.println("<TD><H2>" + "Nom fabricant" + "</H2></TD>");
            sortie.println("<TD><H2>" + "Prix vente" + "</H2></TD></TR>");
            try {
                while (resultat.next()) {
                    //prender les valeurs de la premiere requete
                    String numCat = resultat.getString(1);
                    String des = resultat.getString(2);
                    String nomFab = resultat.getString(3);
                    String prix = resultat.getString(4);
                    sortie.println("<TR><TH>" + numCat + "</TH>");
                    sortie.println("<TD>" + des + "</TD>");
                    sortie.println("<TD>" + nomFab + "</TD>");
                    sortie.println("<TD>" + prix + "</TD></TR>");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            sortie.println("</TABLE>");
        } else
            sortie.print("<H2>Une erreur s'est produite. " +
                         "Veuillez réessayer plus tard.</H2>");

        sortie.println("</BODY></HTML>");
        sortie.close(); // clôturer le flux.
    }

    public void destroy() {
        try {
            connexion.close();
        } catch (Exception e) {
            System.err.println("Problème à la fermeture de" +
                               " la base de données");
        }
    }
}
*********************************

All I want is to share the same connexion instead of opening a new one everything time a new servlet is called.
Thanks

ok, but what if I want to use HTTP sessions? Will that work also?
ASKER CERTIFIED SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Any ideas of how should do it?
Do I need to create session in the init() method?  and which one of the servlet should I put it in?
Thanks in advance