Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
18.9 Sharing Connection Pools
515
18.9 Sharing Connection Pools
In the previous example, each servlet had its own connection pool. This
approach makes sense when different servlets perform substantially different
tasks and thus talk to different databases. However, it is also quite common
for some or all of the servlets on a server to talk to the same database and thus
to share a connection pool. There are two main approaches to sharing pools:
using the servlet context (a servlet specific technique) and using static meth 
ods or singleton classes (a general Java technique).
Using the Servlet Context to Share Connection 
Pools
You can call the servlet 
getServletContext
 method to get an object of type
ServletContext
 that is shared by all servlets on the server (or within a Web
application if your server supports Web applications). This 
ServletContext
object has a 
setAttribute
 method that takes a 
String
 and an 
Object
 and
stores the 
Object
 in a table with the 
String
 as a key. You can obtain the
Object
 at a later time by calling 
getAttribute
 with the 
String
 (this
method returns 
null
 if there is no value associated with the key).
So, for example, a group of servlets that all use the books database could
share pools by having each servlet perform the following steps:
ServletContext context = getServletContext();
ConnectionPool bookPool = 
(ConnectionPool)context.getAttribute("book pool");
if (bookPool == null) {
bookPool = new ConnectionPool(...);
context.setAttribute("book pool", bookPool);
}
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved