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

Struts 1 Java Discussion :

ServletContextEvent et web.xml


Sujet :

Struts 1 Java

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut ServletContextEvent et web.xml
    Bonjour,

    j'aimerais savoir si c'est possible récupérer les valeurs définies dans mon fichier
    web.xml comme suit:


    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
       <context-param>
    		<param-name>pro_dbriver</param-name>
    		<param-value>com.mysql.jdbc.Driver</param-value>
    	</context-param>
    	<context-param>
    		<param-name>pro_dburl</param-name>
    		<param-value>jdbc:mysql://localhost:3306/formacion</param-value>
    	</context-param>
    	<context-param>
    		<param-name>pro_dblogin</param-name>
    		<param-value>formacion</param-value>
    	</context-param>
    	<context-param>
    		<param-name>pro_dbpassword</param-name>
    		<param-value>formacion</param-value>
    	</context-param>
     
    	<listener>
    		<listener-class>dao.login.LoginDAOImpl</listener-class>
    	</listener>
    à n'importe quel moment?


    dans ma classe qui implémente ServletContextListener je fais:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    	static{
    		ServletContextEvent sce;
    		ServletContext application = sce.getServletContext();   
    	}
    j'ai fais un peux de recherche mais je ne trouve pas comment initialiser ma variable sce et encore si ce que je veux faire est possible....


    Je vous remercie d'avance pour vos réponse.

  2. #2
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut
    dans la méthode contextInitialized je fais ça:

    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
    	public void contextInitialized(ServletContextEvent sce) {
     
    		logger.info("Début de méthode: contextInitialized(ServletContextEvent sce)");
     
    		try{	
     
    			ServletContext servletContext = sce.getServletContext();    
     
    			PRO_DRIVER = servletContext.getInitParameter(Const.BD_DRIVER);
    			logger.info("Connexion driver (BDD): " +  PRO_DRIVER);
     
    			PRO_DBURL = servletContext.getInitParameter(Const.BD_URL);
    			logger.info("Connexion url (BDD): " +  PRO_DBURL);
     
    			PRO_LOGIN = servletContext.getInitParameter(Const.BD_LOGIN);
    			logger.info("Connexion url (BDD): " +  PRO_LOGIN);
     
    			PRO_PASSW = servletContext.getInitParameter(Const.BD_PASSWORD);
    			logger.info("Connexion password (BDD): " +  PRO_PASSW);
     
    			Connection cnx = getConection();
    			servletContext.setAttribute("myCnx", cnx);
     
    		}catch(Exception e){}
     
    		logger.info("Fin de méthode: contextInitialized(ServletContextEvent sce)");
     
    	}

    je pense que avec
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Connection cnx = getConection();
    servletContext.setAttribute("myCnx", cnx);
    je garde dans le contexte la connexion, maintenant je ne sais comment la récupéré dans une autre classe ou même dans la propre classe....


    Merci d'avance.

  3. #3
    Expert éminent

    Femme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    5 793
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations forums :
    Inscription : Juillet 2005
    Messages : 5 793
    Points : 7 778
    Points
    7 778
    Par défaut
    Dans une Action, tu peux récupérer myCnx comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Connection cnx = (Connection) this.servlet.getServletContext().getAttribute("myCnx");
    Pour la récupérer dans une autre méthode de ton Listener :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    ServletContext servletContext = sce.getServletContext(); 
    Connection cnx = (Connection) servletContext.getAttribute("myCnx") ;

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut
    Et si je suis dans une classe normale?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    public class LoginDAOImpl implements ILoginDAO, ServletContextListener

    Quand le serveur démarre je passe par la méthode que j'ai dans le dernier post et je configure mas connexion.

    Plus tard il est nécessaire de revenir dans cette classe pour faire une query et j'aimerais récupérer la connexion que j'ai gardé...


    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
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    public class LoginDAOImpl implements ILoginDAO, ServletContextListener {
     
    	private static Log logger = LogFactory.getLog(LoginDAOImpl.class);
     
    	private static Connection con = null;
     
    	/*======================================================================*
    	 * Constante pour la configuration de la connexion à la basse de donnée *
    	 *======================================================================*/
    	 private String PRO_DRIVER;
    	 private String PRO_DBURL;
    	 private String PRO_LOGIN;
    	 private String PRO_PASSW;
     
    	private Connection getConection() throws ExceptionUser {
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Début de méthode: getConection()");
    		}
     
    		try {
    			if (con == null || con.isClosed()){
    				initConection();
    			}
    		} catch (SQLException e) {
    			logger.error(e.getMessage());
    			//TODO implementer cette exception
    			//throw GestorException.newTechnicalException(e);
    		}
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Fin de méthode: getConection()");
    		}
     
    		return con;
    	}
     
    	private void initConection() throws ExceptionUser {
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Début de méthode: initConection()");
    		}
     
    		Driver drv;
     
    			try {
     
    				drv = (Driver) Class.forName(PRO_DRIVER).newInstance();
    				DriverManager.registerDriver(drv);
    				con = DriverManager.getConnection(PRO_DBURL, PRO_LOGIN, PRO_PASSW);
     
    			} catch (Exception e) {
    				logger.error(e.getMessage());
    				//TODO implementer cette exception
    				//throw GestorException.newTechnicalException(e);				
    			}
     
    		if(logger.isDebugEnabled()){
    		   logger.debug("Fin de méthode: initConection()");
    		}
    	}
     
    	public User getUser(String utilisateur, String password) throws ExceptionUser {
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Début de méthode: getUser(String nom, String password)");
    		}
    		//ServletContext sc = ServletContextEvent.getServletContext();
    		//Connection cnx = (Connection)sc.getAttribute("myCnx");
     
    		PreparedStatement pstment = null;
    		ResultSet rset = null;
    		//Connection conect = getConection();
     
    		Connection cnx = (Connection) this.servlet.getServletContext().getAttribute("myCnx");
     
    		String query = "SELECT ID FROM " + Const.TABLE_UTILISATEURS + " WHERE UTILISATEUR = ? AND PASSWORD = ?";
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Query sql: " + query);
    		}
     
    		User theUtilisateur = null;
     
    		try {
    			pstment = conect.prepareStatement(query);
    			pstment.setString(1,utilisateur);
    			pstment.setString(2,password);
     
    			rset = pstment.executeQuery();
     
    			/*======================================================================*
    			 * Il s’agit de vérifier que l’on a obtenu un résultat 					*
    			 *======================================================================*/
    			if (rset.next()){
     
    				theUtilisateur = new User();		
    				theUtilisateur.setId( rset.getString( Const.TABLE_UTILISATEURS_ID ) );
    				theUtilisateur.setNiveauPrivilege( String.valueOf( (rset.getInt(Const.TABLE_UTILISATEURS_NIVEAU_PRIVILEGE)) ) );
    				theUtilisateur.setNom("nom");
     
    				logger.info("Utilisateur trouvé -  Nom: " + "[" + theUtilisateur.getNom() + "]"  + " Password: " + "[" + theUtilisateur.getPassword()+ "]" );
     
    				if(logger.isDebugEnabled()){
    					logger.debug("Id: " + rset.getString("id")); 
    					logger.debug("Nom: " + rset.getString("id"));
    				}
    			}
    		}catch (Exception e){
    			logger.error(e.getMessage());
    			/**Mandamos la excepciones al gestor indicandole el tipo*/
    			//TODO implementer cette exception
    			//throw GestorException.newTechnicalException(e);
     
    		} finally {
    			try {
    				rset.close();
    				pstment.close();
    				conect.close();
    			} catch (SQLException e) {
    				logger.error(e.getMessage());
    				//TODO implementer cette exception
    				//throw GestorException.newTechnicalException(e);
    			}
    		}
     
    		if(logger.isDebugEnabled()){
    			logger.debug("Début de méthode: getUser(String nom, String password)");;
    		}
     
    		return theUtilisateur;
    	}
     
    	@Override
    	public void contextDestroyed(ServletContextEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void contextInitialized(ServletContextEvent sce) {
     
    		logger.info("Début de méthode: contextInitialized(ServletContextEvent sce)");
     
    		try{	
     
    			ServletContext servletContext = sce.getServletContext();    
     
    			PRO_DRIVER = servletContext.getInitParameter(Const.BD_DRIVER);
    			logger.info("Connexion driver (BDD): " +  PRO_DRIVER);
     
    			PRO_DBURL = servletContext.getInitParameter(Const.BD_URL);
    			logger.info("Connexion url (BDD): " +  PRO_DBURL);
     
    			PRO_LOGIN = servletContext.getInitParameter(Const.BD_LOGIN);
    			logger.info("Connexion url (BDD): " +  PRO_LOGIN);
     
    			PRO_PASSW = servletContext.getInitParameter(Const.BD_PASSWORD);
    			logger.info("Connexion password (BDD): " +  PRO_PASSW);
     
    			Connection cnx = getConection();
    			servletContext.setAttribute("myCnx", cnx);
     
    		}catch(Exception e){}
     
    		logger.info("Fin de méthode: contextInitialized(ServletContextEvent sce)");
     
    	}
     
     
    }

  5. #5
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut
    Je te remercie beaucoup!

    Depuis l'action je la récupéré la configuration e j'envoie tout ver la classe que est posté dans l'exemple anterieur

    Merci encore

  6. #6
    Expert éminent

    Femme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    5 793
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations forums :
    Inscription : Juillet 2005
    Messages : 5 793
    Points : 7 778
    Points
    7 778
    Par défaut
    De rien.

  7. #7
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut
    Une toute dernière question:

    Si j'arrête le serveur, je passe par la méthode
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    contextDestroyed(ServletContextEvent arg0)

    faut-il détruire la connexion? ou elle se ferme automatiquement???

    Même si il n'est pas nécessaire de détruire la connexion? comment la récupérer dans dans cette classe?

    Merci.

  8. #8
    Expert éminent

    Femme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    5 793
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations forums :
    Inscription : Juillet 2005
    Messages : 5 793
    Points : 7 778
    Points
    7 778
    Par défaut
    Je te l'ai mis précédemment.
    Tu peux la récupérer comme ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    ServletContext servletContext = sce.getServletContext(); 
    Connection cnx = (Connection) servletContext.getAttribute("myCnx") ;
    et je pense qu'il faut effectivement stopper la connexion dans la méthode contextDestroyed.

  9. #9
    Membre régulier
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    277
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 277
    Points : 105
    Points
    105
    Par défaut
    Oui c'est juste, je m' excuse ,


    Merci :

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [TOMCAT] parametrage du fichier web.xml
    Par sebos63 dans le forum Tomcat et TomEE
    Réponses: 12
    Dernier message: 06/05/2010, 12h09
  2. [Tomcat] configuration d'une page d'erreur dans web.xml
    Par Super Castor dans le forum Tomcat et TomEE
    Réponses: 3
    Dernier message: 08/04/2009, 15h58
  3. [Débutant][Application web] : web.xml + includes jsp
    Par silver_dragoon dans le forum Servlets/JSP
    Réponses: 3
    Dernier message: 12/02/2004, 20h46
  4. [TomCat][sécurité]config fichier web.xml
    Par liomac dans le forum Tomcat et TomEE
    Réponses: 6
    Dernier message: 24/09/2003, 15h46
  5. [JBUILDER 9][WEBAPPS] web.xml importé.
    Par proner dans le forum JBuilder
    Réponses: 3
    Dernier message: 17/09/2003, 21h04

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