I want to use init() to do some stuff with config and context init-params in my servlet. One of the things I want to do is open a DB connection, which I believe is quite a common use of init().
Anyway, I am learning about all this stuff by reading HF Servlets and JSP, in which I seem to remember it saying that instance variables in servlets are a bad idea. I only actually _need_ the DB connection briefly in order to read some configuration data in, so I could actually keep that object method local within init(). However, I would like to keep a copy of the connection parameters so I can display them in a JSP later, but the only way my small brain can see to do this is to store them in an instance variable (like HashMap). I can't, for example, do
because at the init() stage there is no context!
Can anyone suggest what to do here? Where can I store these params for later without using an instance variable? Do I even need to? I'm confused
The reason I didn't think I had a context during init() was because doing so caused a null pointer exception. I have now realised that the reason for this was that I had overridden init(ServletConfig) instead of just init(). Doh!
I had thought of a context listener, but need to read up on that a little more! That may be the way I go ultimately.
Yes this will be a production app, but the database connection is not actually used by the service methods. It is simply used to load some extra, more complex, config data during init() which I don't think is appropriate to place in the deployment descriptor. Also, by keeping this data in the DB, rather than in the DD, that allows me to refresh that info without restarting the app by asking it to re-read the DB using some kind of refresh request. Do you think this sounds appropriate.
Cheers Ben. All this stuff is taking a while to sink in. Most of my Java before was back-end stuff with the odd bit of lame servlet-ing now and then, but I'm really trying to get up to speed on the web side now - there is much to learn!
I only actually _need_ the DB connection briefly in order to read some configuration data in, so I could actually keep that object method local within init(). However, I would like to keep a copy of the connection parameters so I can display them in a JSP later, but the only way my small brain can see to do this is to store them in an instance variable (like HashMap).
That's exactly what I would do. It might be dangerous to keep a live Connection object around, but there is no problem with having instance variables as long as you don't modify them after the end of init(). It doesn't matter if a thousand threads concurrently access the same HashMap as long as none of them modify it.
That works. Just remember that when you decide to refresh the values from the database, you need to create a new Map and replace the old one with it. Do NOT modify the old one, as some JSPs might be accessing it at the moment.