[Logo]
Forums Register Login
ServletContext, its attribute to be shared for all over the Servlet?
Hello everyone...!!

Actually I do have a project root,
and I do have a xml file of my DB configuration that i put inside "/WEB-INF".

Thus, each time there is a jsp call a Servlet, and that Servlet want to do Transaction to the DB,
it should Read the Location of the DB first.

So, for every Servlet I should put these lines of source codes.



Yes, The main point here is the getDBContext() ---> Which would be passed over my DB Java Class later on. When I want to use it later each time I want to do transaction (update, delete, and so on).

But I feel this is not efficient. Since It feel too much. Is there any short way arround?
Could any one enlighten me with this concept?
Note below points


- Once a servle context attribute is shared, its available to all servlets in the application, you don't need to set if from every servlet.
- Instead of setting the context attributes (specially realted to configuration) from a servlet, you can implement a ServletContextListner and do it from there
- Instead of parsing the xml file every time, do it once (in your listner) create a configuration object and make it available as context attribute.

The best way is,
Instead of managing database connections/configuration this way, use a connection pool and make it available as a JNDI resource, tomcat supports it. look here
 
sudhir nim wrote:Note below points
- Once a servle context attribute is shared, its available to all servlets in the application, you don't need to set if from every servlet.


oh, is it right? I mean, I never thought it
So if let say I have couple servlets that need to do transactions with the DB.
What I gotta put is just the getDBContext() rather than setDBContext() again in other servlet...

because, as you said, the servlet context is initiated (shared) first time, and now become shared for everyone-else...
(2 likes)
 

What I gotta put is just the getDBContext() rather than setDBContext() again in other servlet...


Yes, right.

Consider my other points as well regarding a listner and connection pool bound to JNDI
 
sudhir nim wrote:

What I gotta put is just the getDBContext() rather than setDBContext() again in other servlet...


Yes, right.
Consider my other points as well regarding a listner and connection pool bound to JNDI


thanks a lot sudhir nim!
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Oct 16, 2017 16:40:36.