Hi everyone, I have problems reading data from a MySQL-Database through a Servlet. The Connection works; it must be a simple step. I don't know how to do the last step. The ContextListener checks the Connection at startup. Heres my Code:
If I am not mistaken, your question is "How can I get something (a Connection) out of the ServletContext in a servlet?" Well, this is hardly a JDBC question, so perhaps I didn't understand your problem.
So, let me suggest that in your servlet you shouldn't be importing any com.mysql classes. Just like in your context listener, you should be importing those classes from the java.sql package instead.
Also, in web applications which are going to have more than one user, it is not a good idea to have only a single Connection available to those users. Typically you configure a connection pool and have the servlet get a connection from the pool. But I see your code is a demo, so perhaps you planned to do that later.
Joined: Jul 22, 2008
Thanks for your answer. You are right: connection pooling is a further feature, first we want to implement the basics.
I will follow your hint with the com.mysql-Classes, I think this was a mistake trough Eclipse; i clicked the wrong classes to import.
So, I'm sorry if I asked my question wrong; here step by step what I think it has to be (the way I coded it)...
*) I start the servlet. The context-listener starts and checks if the connection works. If it works, the connection is established and works for the whole "underlying" webapp. Right?
*) With the start of the servlet I wan't to get data out the SQL. So I can use the connection provided and established by the context-listener. Right? (Uh, this might be wrong...)
But I don't know how to get access to the DataSource-Object (Is it an object?)
Originally posted by martin weber: But I don't know how to get access to the DataSource-Object (Is it an object?)
Of course it's an object. It's not a primitive so it must be an object. You put it into the servlet context in your listener class, right? So you take it out of the servlet context in your servlet. Step 1: get the servlet context. Step 2: get the "datasource" attribute from that.