Originally posted by Jason Davies:
You're better off putting the creation of the JDBC Connection inside the doGet method. I would also advise the use of a connection pool if you're worried about performance.
[i]It is entirely possible that we will want to initialize the servlet with some data whenit is instantieted. Once the container creates the servlet instance, it calls init(ServletConfig) method on this newly created instance. The servlet is initialized after the init() method returns.
For example, if we wanted to create a database connection in the servlet we would not want to hard-code the user/pwd and the database URL in the servlet. the init() method allows us to specify them in the deployment descriptor. It does not make sense to initialize an object repetedly; therefore, the framework guarantees that the servlet container will call the init() method once and only once on a servlet instance.
SCWCD study kit
Originally posted by Andres Gonzalez:
Andres: I'd put it in the init method of the servlet
Gregg: Very bad idea in my opinion because of mutliple requests on the same object. Can cause all sorts of problems. I would go with Jason on this one...
Then I require clarification on the question:
I probably misunderstood the question, but I still think a connection to a database should be made in the init method. In fact, I've used this ConnectionBroker before, and the example they have show they made a connection in the init method and put that object in the context, just as I explained before.
Jason:You're better off putting the creation of the JDBC Connection inside the doGet method.
I don't understand why this solution. If you click on a link that invokes your servlet, for example, it'll generate a GET request and you will be creating a JDBC connection again. I still don't think this is a good idea. You should create a broker with X number of connections once and reuse connections everytime you need access to the database. As gregg said, you should release that connection (close()) once you're done (connection pooling)
[ September 18, 2003: Message edited by: Andres Gonzalez ]
Originally posted by Jeroen Wenting:
Your understanding is false.
Even when you use a broker (connection pool is the correct word) you still need to return the connection to the pool when you exit your request method.
This is the same as when you create the connections yourself in each request (again, CLOSE ALL CONNECTIONS BEFORE EXITING ALWAYS!).
Whether the connection pool then closes the connection or keeps it alive is not your concern, but if you fail to return it to the pool you have exactly the same problems as when you had no pool at all as the pool will be constantly opening new connections because the old ones are never released back to it.
Andres: As gregg said, you should release that connection (close()) once you're done (connection pooling)