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 :

2 sessions non hermétiques


Sujet :

Servlets/JSP Java

  1. #1
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut 2 sessions non hermétiques
    Bonjour, le problème que j'ai provient du fait que les sessions se mélangent lorsque 2 clients se connectent simultanément au site.
    A la page index.jsp, le client entre son ligin/mot de passe et créé une session d'après la requête dans ma servlet Authentication. (request.getSession()) Je stocke mes attributs directement dans la session. (session.setAttribute("nom", valeur) Si 2 clients sont connectés en même temps, les attributs sont écrasés. Le premier a avoir écrit se retrouve avec les valeurs du 2eme. J'aurais voulus avoir 2 fois le même attribut mais dans deux sessions différentes. Vous comprenez ? Peut-être se servir de l'id ?

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Les session sont indépendantes. Vous avez bien testé avec deux machines différentes ou deux navigateurs différents?

  3. #3
    Modérateur
    Avatar de OButterlin
    Homme Profil pro
    Inscrit en
    Novembre 2006
    Messages
    7 313
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 7 313
    Billets dans le blog
    1
    Par défaut
    Si tu as lancé 2 fois le navigateur sur le même poste ou si tu utilises 2 onglets avec la même application, les sessions sont communes (en tout cas avec Firefox).
    Pour ne pas écraser les informations de session, il va falloir imaginer un mécanisme d'identification de ton client et rattacher les valeurs à cet identifiant (avec une Map par exemple).
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  4. #4
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Si tu désactive les cookies et que tu utilise correctement les URLrewriting dans tes pages, partir de deux fenêtre séparée, sans session au départ, te mènera à avoir deux sessions distincte. M'enfin pour ce genre de test, ouvrir deux navigateurs séparés reste plus simple

  5. #5
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Merci pour vos réponses, c'est vrai qui firefox écrase les sessions.
    Cela dit, je n'ai pas entièrement résolu mon problème :
    Lorsque les clients font des requêtes sur ma base de données j'ai beaucoup de resultset is closed. Je le suis renseigné là-dessus, et de ce que je comprend, il faut que sérialise tous mes composants y compris ma connexion avec le SGBD ?

  6. #6
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    la serialisation n'es nécessiare que si tu veux préserver les session à l'arret de ton conteneur ou si tu désire supporter le clustering. Le "resultset is closed" n'a, a priori, rien à voir avec la session.

  7. #7
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Aie ça ne me rassure pas du tout. A partir du moment où j'ai introduit la notion de session dans le projet, l'EDI m'a affiché pleins de messages du type "IOException" lors du chargement des sessions persistantes: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException:

    J'ai alors sérialisé toutes mes classe métiers.
    J'avoue ne pas trop maitriser le problème, mais les resultset is closed me génère trop d'erreurs.
    D'où ça peut venir dans mon cas ?
    Avez-vous besoin de quelques sources ?

    Merci d'avance

  8. #8
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    d'un problème de concurence mal gérée dans certaines de vos classes en général. Comment ça se fait que votre session est systématiquement sérialisée? Vous êtes en contexte de cluster?

    Un ResultSet dépend d'un DataSource, qui dépend d'une connexion base de données. Ni l'un ni l'autre ne peuvent donc être sérialisé!! A priori donc, si vous n'y coupez pas à la sérialisation des session (cluster) il faudra envisager de retirer tout ce qui est resultset de la session.

  9. #9
    Membre Expert
    Homme Profil pro
    Dév. Java & C#
    Inscrit en
    Octobre 2002
    Messages
    1 414
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Dév. Java & C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2002
    Messages : 1 414
    Par défaut
    Bonjour,

    Maintenez-vous des resultsets ouverts entre deux appels?

    Le message "resultset is closed" survient dans une code Java?

    Si oui, pourriez-vous nous montrer le code où l'erreur survient?

  10. #10
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Non, je ne suis pas en contexte de cluster.
    Dans le premier temps, aucune classe n'est sérialisée. Je développe sous netbeans et celui-ci m'a affiché des message dans la console lorsque j'ai travaillé avec les sessions.

    GRAVE: "IOException" lors du chargement des sessions persistantes: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: component.Family
    java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: component.Family

    session.setAttribute("currentFamily", family);

    A ce moment là, j'ai sérialiser mes classes métier. Pourquoi veut-il sérialiser la classe ?

    Si ça vous intéresse, voici le printStackeTrace lorsque j'enregistre le projet :

    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
    GRAVE: "IOException" lors du chargement des sessions persistantes: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: component.Family
    java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: component.Family
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1333)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at java.util.ArrayList.readObject(ArrayList.java:593)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
            at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1846)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1441)
            at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:942)
            at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:394)
            at org.apache.catalina.session.StandardManager.load(StandardManager.java:321)
            at org.apache.catalina.session.StandardManager.start(StandardManager.java:637)
            at org.apache.catalina.core.StandardContext.start(StandardContext.java:4438)
            at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3190)
            at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:918)
            at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:360)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:196)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
            at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
            at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
            at java.lang.Thread.run(Thread.java:619)
    Caused by: java.io.NotSerializableException: component.Family
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
            at java.util.ArrayList.writeObject(ArrayList.java:570)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
            at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1517)
            at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:959)
            at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:517)
            at org.apache.catalina.session.StandardManager.unload(StandardManager.java:463)
            at org.apache.catalina.session.StandardManager.stop(StandardManager.java:667)
            at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4573)
            at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3184)
            ... 20 more
    4 nov. 2010 09:25:56 org.apache.catalina.session.StandardManager start
    GRAVE: Exception au chargement des sessions depuis le stockage persistant (persistent storage)
    java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: component.Family
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1333)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at java.util.ArrayList.readObject(ArrayList.java:593)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
            at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1846)
            at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1441)
            at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:942)
            at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:394)
            at org.apache.catalina.session.StandardManager.load(StandardManager.java:321)
            at org.apache.catalina.session.StandardManager.start(StandardManager.java:637)
            at org.apache.catalina.core.StandardContext.start(StandardContext.java:4438)
            at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3190)
            at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:918)
            at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:360)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:196)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
            at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
            at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
            at java.lang.Thread.run(Thread.java:619)
    Caused by: java.io.NotSerializableException: component.Family
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
            at java.util.ArrayList.writeObject(ArrayList.java:570)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
            at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1517)
            at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:959)
            at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:517)
            at org.apache.catalina.session.StandardManager.unload(StandardManager.java:463)
            at org.apache.catalina.session.StandardManager.stop(StandardManager.java:667)
            at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4573)
            at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3184)
            ... 20 more



    Concernant les problèmes de BDD, je ne retrouve plus le fichier log, je vous en envoie un bout lorsque l'erreur revient. Voici la servlet qui la génère (je ne vois que ça). Il s'agit d'une recherche par mot clé.
    Ma base de données était un singleton, ça semble être mieux depuis que j'ai retiré cette particularité.

    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
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
     
    public class SearchEngine extends HttpServlet {
     
        /** 
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            HttpSession session = request.getSession();
            try {
                response.setContentType("text/html;charset=UTF-8");
                ServletContext sc = getServletContext();
                RequestDispatcher rd;
                ArrayList<Family> allowedFamilies = ((ArrayList) session.getAttribute("allowedFamilies"));
                ArrayList<Integer> selectedFamilies = (ArrayList<Integer>) session.getAttribute("selectedFamillies");
                ArrayList<String> selectionnableBoxes = new ArrayList<String>();
                String[] params = null;
                params = request.getParameter("search").split(" ");
                session.setAttribute("lastParam", request.getParameter("search"));
                if (params.length==0||params[0].equals("")) {
                    ArrayList<Integer> indexList = (ArrayList<Integer>) session.getAttribute("selectedFamillies");
                    String state = null, currentPage = (String) session.getAttribute("currentPage");
                    if (currentPage.equals("consult")) state = null;
                    else if (currentPage.equals("order")) state = "RANGEE";
                    else if (currentPage.equals("return")) state = "SORTIE";
                    else if (currentPage.equals("destroy")) state = "RANGEE";
     
     
                    if (state!= null) selectionnableBoxes = EngineMethods.viewableBoxesCollectionMaker(indexList, (ArrayList<Family>)session.getAttribute("allowedFamilies"), state);
                    else selectionnableBoxes = EngineMethods.viewablBoxesCollectionMaker(indexList, (ArrayList<Family>)session.getAttribute("allowedFamilies"));
                }
                else {                
                    DataBase db = DataBase.getIstance();
                    db.connection();
                    ResultSet res;
                    //long time = System.currentTimeMillis();
                    //begin querry
                    String querryCom = "SELECT identifiantBoite FROM CloneBoite WHERE ";
     
                    //famillies restrictions (must first restriction)
                    String familiesRestriction = "";
                    for (int i=0; i<selectedFamilies.size(); i++) {
                        if (i!=0) familiesRestriction += "OR ";
                        else familiesRestriction += "(";//i==0
                        familiesRestriction += "famille = '"+allowedFamilies.get(selectedFamilies.get(i)).getIdentifier()+"'";
                        if (i==selectedFamilies.size()-1) familiesRestriction += ")";
                    }
     
                    querryCom += familiesRestriction;
     
     
                    String wordingsRestriction = "";
     
                    //Starting wording restrictions
     
                    //identifier
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND (identifiantBoite LIKE '%"+params[i]+"%'";
                        else wordingsRestriction += " OR identifiantBoite LIKE '%"+params[i]+"%'";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
     
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //archiving
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND (libelleArchivage LIKE '%"+params[i]+"%'";
                        else wordingsRestriction += " OR libelleArchivage LIKE '%"+params[i]+"%'";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //2
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND (libelle2 LIKE '%"+params[i]+"%'";
                        else wordingsRestriction += " OR libelle2 LIKE '%"+params[i]+"%'";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //3
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND (libelle3 LIKE '%"+params[i]+"%'";
                        else wordingsRestriction += " OR libelle3 LIKE '%"+params[i]+"%'";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))//check if result is already into display tab
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
     
     
                    //in identifier and archiving
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelleArchivage LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelleArchivage LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
                    //in identifier and 2
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle2 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
                    //in identifier and 3
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle3 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle3 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                   //in archiving and 2
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle2 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //in archiving and 3
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //in 2 and 3
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle2 LIKE '%"+params[i]+"%' OR libelle3 LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR libelle3 LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
                    //in identifier archiving 2
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((identifiantBoite LIKE '%"+params[i]+"%' OR  libelle2 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //in identifier archiving and 3
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((identifiantBoite LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //in identifier 2 and 3
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR identifiantBoite LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
                    //in 2 archiving and 3
     
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
        //            identifier archiving 2 and 3
                    wordingsRestriction = "";
                    for (int i=0; i<params.length; i++) {
                        if (i==0)wordingsRestriction += " AND ((identifiantBoite LIKE '%"+params[i]+"%' OR  libelle2 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%' OR libelle3 LIKE '%"+params[i]+"%')";
                        else wordingsRestriction += " OR (libelle2 LIKE '%"+params[i]+"%' OR  libelle3 LIKE '%"+params[i]+"%' OR libelleArchivage LIKE '%"+params[i]+"%' OR libelle3 LIKE '%"+params[i]+"%')";
                        if (i==params.length-1) wordingsRestriction += ");";
                    }
                    System.out.println(querryCom+wordingsRestriction);
                    try {
                        res = db.getResult(querryCom+wordingsRestriction);
                        Object[][] data = DataBase.getObjects(res, 1);
                       // System.out.println("Reçu de la BDD : "+(System.currentTimeMillis()-time));
                        for (int i=0; i<data.length; i++) {
                            boolean found = false;
                            for (int j=0; j<selectionnableBoxes.size(); j++) {
                                if (selectionnableBoxes.get(j).equals(data[i][0].toString()))
                                    found = true;
                            }
                            if (!found) {
                                selectionnableBoxes.add(data[i][0].toString());
                                System.out.println(data[i][0].toString());
                            }
                        }
                    }
                    catch (SQLException sql) {sql.printStackTrace();}
     
     
                }
                session.setAttribute("selectionnableBoxes", selectionnableBoxes);
                session.setAttribute("necessariespages", selectionnableBoxes.size()/100 + 1 );
                session.setAttribute("currentPageNumber", 1);
                String currentPage = (String) session.getAttribute("currentPage");
                request.setAttribute("from", "SearchEngine");
                //rd = sc.getRequestDispatcher("/"+currentPage+".jsp");//to have the first char to upper case. Servlet name start with an upper case
                rd = sc.getRequestDispatcher("/"+currentPage.substring(0, 1).toUpperCase()+currentPage.substring(1));//to have the first char to upper case. Servlet name start with an upper case
                rd.forward(request, response);
            }
            catch (NullPointerException np) {np.printStackTrace();
                ServletContext sc = getServletContext();
                RequestDispatcher rd;
                rd = sc.getRequestDispatcher("/index.jsp");
                rd.forward(request, response);
            }
            catch (Exception e) {e.printStackTrace();}
        }

  11. #11
    Membre Expert
    Homme Profil pro
    Dév. Java & C#
    Inscrit en
    Octobre 2002
    Messages
    1 414
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Dév. Java & C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2002
    Messages : 1 414
    Par défaut
    Concerant ta BDD, j'ai quelques remarques:

    1. Attention si le paramètre contient un apostrophe, ton interrogation SQL n'est pas correcte.
    2. Qui libère les ressources Statement et ResultSet?



    Pour la sérialisation, String et Integer pas de problème. La classe Family est-elle marquée comme Serializable.

  12. #12
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    pour le point 1, tu peux ignorer l'erreur. C'est juste la serialisation /deserialsiation qui a lieu lors de l'arret / démarrage de la webapp pour preserver les session d'une exécution à une autre. Si ce n'est pas vital pour toi, ne t'en occupe pas.
    Rajotue ceci dans ton context.xml et tomcat n'essaieras plus
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
        <Manager className="org.apache.catalina.session.PersistentManager"
          debug="0" distributable="false" saveOnRestart="false">
            <Store className="org.apache.catalina.session.FileStore"/>
        </Manager>
    point 2)
    ton code est "bizzare". Tes resultset ne sont jamais fermé, ta connexion DB non plus. tu peux nous expliquer comment tu gère tes connexions base de donnée?

  13. #13
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Citation Envoyé par jowo Voir le message
    Concerant ta BDD, j'ai quelques remarques:

    1. Attention si le paramètre contient un apostrophe, ton interrogation SQL n'est pas correcte. //J'ai un replaceAll qui corrige la requette
    2. Qui libère les ressources Statement et ResultSet? //Elles ne sont jamais libérées manuellement



    Pour la sérialisation, String et Integer pas de problème. La classe Family est-elle marquée comme Serializable.

  14. #14
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Citation Envoyé par tchize_ Voir le message
    ton code est "bizzare". Tes resultset ne sont jamais fermé, ta connexion DB non plus. tu peux nous expliquer comment tu gère tes connexions base de donnée?
    Voici ma classe DataBase :
    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
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
     
    public class DataBase implements Serializable{
        private String url, userName, password;
        private Statement st;
        private Connection con;
     
        /**
         * @author Brice
         * Constructor
         */
        private DataBase () throws SQLException {
            //attributes constructor
            this.userName = "root";//user of database
            this.password = "a";//password to connect database
            this.url = "jdbc:odbc:Javarch";//database adress
        }
     
        public static DataBase getIstance () {
            /*if (instance==null)
                try {instance = new DataBase();} catch (SQLException ex) {}*/
            try {return new DataBase();}catch (SQLException ex) {ex.printStackTrace();return null;}
        }
        /**
         * @param void
         * @return void
         * Connect the program to database
         */
        public void connection () throws SQLException {
            try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");}
            catch (ClassNotFoundException e) {System.out.println("ClassNotFoundException");
            }
            con = DriverManager.getConnection(url, userName, password);
            st = con.createStatement();
        }
     
        /**
         * @param String request
         * @return ResultSet
         * Execute a querry request on database and return the result
         */
        public ResultSet getResult (String request) throws SQLException {
            return st.executeQuery(request);
        }
     
        /**
         * ju-
         * @param request
         * @throws SQLException
         */
        public void update(String request) throws SQLException {
            st.executeUpdate(request);
        }
     
        /**
         * @param void
         * @return void
         * Close database connection
         */
        public void close() throws SQLException {
            con.close();
        }
     
        public static Object [][] getObjects(ResultSet theResultSet, int numberField) throws SQLException {
     
            int size =0;
            ArrayList<Object> [] listArrays = new ArrayList[numberField];//arrayList collection
            //building arrayList collection
            for (int i=0; i<numberField; i++) {
                listArrays[i] = new ArrayList <java.lang.Object>();
            }
     
            while(theResultSet.next()) {
              size++;//match number rows from the database result
              for (int i=0; i<numberField; i++) {
                  listArrays[i].add(theResultSet.getString(i+1));
              }
            }
            Object[][] ret = new Object[size][numberField];
            for (int i=0; i<listArrays[0].size(); i++) {
                for (int j=0; j<listArrays.length; j++) {
                    ret[i][j] = listArrays[j].get(i);
                }
            }
            return ret;
        }
     
        /**
         *
         * @param str
         * @return formatted string to insert data into database
         * Add ' before string parameter and ' after string parameter in order to insert return into an sql insert request
         */
        public static String[] addSimpleCotes(String[] str) {
            String[] ret = new String[str.length];
            for (int i=0; i<ret.length; i++) {
                try {
                    if (str[i].equals("")) ret[i] = "NULL";
                    else ret[i] = "'"+str[i]+"'";
                }
                catch (NullPointerException ex) {}
            }
            return ret;
        }
     
        public static String addSimpleCotes(String str) {
            return "'"+str+"'";
        }
     
        public static String toLogConversionIS(String dateDB){
            String[] cutDate = new String[3];
            String resCutDate = "", ret = "";
            try {
                cutDate = dateDB.split("-");
                resCutDate = cutDate[2]+"/"+cutDate[1]+"/"+cutDate[0];
                try {
                    if(cutDate[0].length()==4 && cutDate[1].length()==2 && cutDate[2].length()==2 && Integer.parseInt(cutDate[2])>=1 && Integer.parseInt(cutDate[2])<=31 && Integer.parseInt(cutDate[1])>=1 && Integer.parseInt(cutDate[1])<=12){
                        ret = resCutDate;
                    }
                }
                catch (NumberFormatException ex) {}
            }
            catch(ArrayIndexOutOfBoundsException error){}
            return ret;
        }
     
        public static String toDBConversionIS(String datelog){
            String[] cutDate = new String[3];
            String resCutDate = "", ret = "";
            try {
                cutDate = datelog.split("/");
                resCutDate = cutDate[2]+"-"+cutDate[1]+"-"+cutDate[0];
                try {
                    if((0<Integer.parseInt(cutDate[2])&& Integer.parseInt(cutDate[2])<3000) &&
                            (Integer.parseInt(cutDate[1])>0 && Integer.parseInt(cutDate[1])<=12) &&
                            (Integer.parseInt(cutDate[0])>=1 && Integer.parseInt(cutDate[0])<=31)){//check if format is correct with number (1<=month<=12 and day 1<=day<=31)
                        ret = resCutDate;
                    }
                    else JOptionPane.showMessageDialog(null, "Le format de la date est incorrect", "", JOptionPane.ERROR_MESSAGE);
                }
                catch (NumberFormatException ex) {System.out.println("16");}
            }
            catch(ArrayIndexOutOfBoundsException error){
                try {
                    cutDate = datelog.split("-");
                    if((0<Integer.parseInt(cutDate[0])&& Integer.parseInt(cutDate[0])<3000) &&
                            (Integer.parseInt(cutDate[1])>0 && Integer.parseInt(cutDate[1])<=12) &&
                            (Integer.parseInt(cutDate[2])>=1 && Integer.parseInt(cutDate[2])<=31)){
                        ret = datelog;//parameter is already correct
                    }
     
                }
                catch(ArrayIndexOutOfBoundsException exp){
                    JOptionPane.showMessageDialog(null, "Le format de la date est incorrect", "", JOptionPane.ERROR_MESSAGE);
                }
                catch (NumberFormatException nfe) {}
            }
            return ret;
        }
     
        /**
         *
         * @param str
         * @return
         * This routin allows to insert "'" characters in fields and insert into database
         */
        public static String translateSimpleCote (String str) {
            String ret = str.replaceAll("\'", "\\\\\'");
            return ret;
        }
     
        public static String[] translateSimpleCote (String[] str) {
            String[] ret = new String[str.length];
            for (int i=0; i<ret.length; i++) {
                ret[i] = translateSimpleCote(str[i]);
            }
            return ret;
        }
     
        public static String escape(String str) {
            String ret = str;
            if (str.contains("_")||str.contains("%")) {
                ret  = "$"+str;
            }
            return ret;
        }
    }
    Il faudrait donc qu'à chaque fois que j'ai utilisé mon resultset (une fois transformé en tableau d'objet), je fasse res.close() ?

  15. #15
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    A noter que l'ensemble de mes classes métiers ont un DAO (FamilyDAO par exemple) et les DAO hértent tout d'une supercalsse DAO qui a un attribut protected DataBase et ResultSet.
    Je devrais en déclarer un à chaque calsse fille ? (dommage pour la généralisation ici)

  16. #16
    Modérateur
    Avatar de OButterlin
    Homme Profil pro
    Inscrit en
    Novembre 2006
    Messages
    7 313
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 7 313
    Billets dans le blog
    1
    Par défaut
    Dans un contexte web, l'usage veut qu'on acquiert une connexion, on l'utilise, et on la ferme.
    Il ne faut pas perdre de vue que le serveur n'a aucune idée de qui est là ou ne l'est plus, maintenir une connexion au-delà du request/response peut s'avérer gourmand en connexion DB.
    Avant de fermer une connexion, idem, l'usage voudrait qu'on ferme les ressources liées (ResultSet, Statement, PraparedStatement, etc...).
    Dans la majorité des cas, fermer la connexion ferme tout, même si c'est moins "propre".

    D'habitude, on code une classe utilitaire pour l'acquisition de l'objet Connection (à moins d'avoir un pool de connexion auquel cas on fera un peu autrement via une Datasource).
    Les ressources sont définies dans la méthode utilisatrice ce qui évitera des problèmes de concurrence, on arrive à une structure du style
    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
     
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try
    {
       connection = LaClasseUtilitaire.getConnection();
       pstmt = connection.prepareStatement("...");
       rs = pstmt.executeQuery();
       while (rs.next())
       {
          ...
       }
    }
    catch (Exception e)
    {
    }
    finally
    {
       LaClasseUtilitaire.closeResource(rs);
       LaClasseUtilitaire.closeResource(pstmt);
       LaClasseUtilitaire.closeResource(connection);
    }
    (dans le genre )
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  17. #17
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Citation Envoyé par OButterlin Voir le message
    Dans un contexte web, l'usage veut qu'on acquiert une connexion, on l'utilise, et on la ferme.
    Il ne faut pas perdre de vue que le serveur n'a aucune idée de qui est là ou ne l'est plus, maintenir une connexion au-delà du request/response peut s'avérer gourmand en connexion DB.
    Avant de fermer une connexion, idem, l'usage voudrait qu'on ferme les ressources liées (ResultSet, Statement, PraparedStatement, etc...).
    Dans la majorité des cas, fermer la connexion ferme tout, même si c'est moins "propre".

    D'habitude, on code une classe utilitaire pour l'acquisition de l'objet Connection (à moins d'avoir un pool de connexion auquel cas on fera un peu autrement via une Datasource).
    Les ressources sont définies dans la méthode utilisatrice ce qui évitera des problèmes de concurrence, on arrive à une structure du style
    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
     
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try
    {
       connection = LaClasseUtilitaire.getConnection();
       pstmt = connection.prepareStatement("...");
       rs = pstmt.executeQuery();
       while (rs.next())
       {
          ...
       }
    }
    catch (Exception e)
    {
    }
    finally
    {
       LaClasseUtilitaire.closeResource(rs);
       LaClasseUtilitaire.closeResource(pstmt);
       LaClasseUtilitaire.closeResource(connection);
    }
    (dans le genre )

    Du coup pour transformer mon resultset en tableau d'objet je met tout dans le getresult. Ce qui fait que le résultset reste toujours encapsulé dans mon database. C'est bien ça l'idée ?

  18. #18
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    alors
    -> le driver odbc: un très très très mauvais idée à utiliser dans une web applicaiton. Ce driver n'est pas multi threadé, ca veux dire que les requetes sont mise à la queue l'une derrière l'autre dessus. Question perfs, pas génial

    -> concernant tes resultset, si il sont "closed" , c'est qu'on a fermé la connexion. en général, c'estdu à un appel à con.close(). Hors je ne vois nulle part dans le code de la servlet où tu cloture la connexion. Résultat tu va saturer la mémoire en terme de connexions et resultset et, ben pas étonnant qu'à la fin un driver aussi moisi que le pont jdbc/odbc finisse par péter les plombs.

    donc

    1) bien tout fermer proprement quand tu as fini ta requete
    2) si toujours exception, nous poster le stacktrace de l'exception et le code qui va avec
    3) si possible se débarasser de ce driver et utiliser un driver spécifique à ta base de donnée.

  19. #19
    Membre chevronné
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2009
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2009
    Messages : 540
    Par défaut
    Ca y est c'est fait. Le souci maintenant c'est que la connexion échoue une fois sur 3. Un nouveau driver corrigerait le problème ?

    J'ai téléchargé celui là http://www.mysql.fr/downloads/connector/j/ (jdbc)
    ici http://www.mysql.fr/products/connector/

  20. #20
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    un bon reflexe, pour qu'on puisse répndre, c'est de poster tes messages d'erreur.

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 3 123 DernièreDernière

Discussions similaires

  1. Variable session non retenue / problème sur Firefox
    Par hatembr dans le forum Langage
    Réponses: 10
    Dernier message: 25/04/2007, 17h22
  2. Réponses: 5
    Dernier message: 24/10/2006, 11h56
  3. session non reconnue sur autre pc
    Par Makari dans le forum Langage
    Réponses: 6
    Dernier message: 24/08/2006, 13h54
  4. Ajouter une clé pour une session non ouverte
    Par prgasp77 dans le forum Windows
    Réponses: 4
    Dernier message: 29/10/2005, 00h26
  5. [Session Context] session non transmise
    Par patricetouner dans le forum Servlets/JSP
    Réponses: 3
    Dernier message: 29/12/2004, 14h56

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