Java Reference
In-Depth Information
Now that you have created and understand the
ConnectionPoolServlet
, you can put it to use
with another example. This example is based on your
TitleListServlet
, except that you will
do a generic query with no request parameters. There are two important changes to this servlet.
The first is how it gets a connection and the second is how it releases that connection.
The
TitleListGlobalPooledServlet
gets a
Connection
object by calling the
ServletContext.getAttribute()
method, passing it the key
“CONNECTION_POOL”
, which
returns a reference to the
ConnectionPool
object. It can then call the
ConnectionPool.getConnection()
method to get a JDBC connection:
7
// Get a reference to the ConnectionPool from the Global
// ServletContext
pool =(ConnectionPool)
getServletContext().getAttribute(“CONNECTION_POOL”);
// Get a connection from the ConnectionPool
con = pool.getConnection();
When the servlet finishes with the connection, it must release it. This is done by calling the
ConnectionPool
's
releaseConnection()
method:
// Release the connection
pool.releaseConnection(con);
That is all there is to it. After you are finished with the
ConnectionPool
, it still resides in the
ServletContext
waiting on future requests. You'll find the entire source for the
TitleListGlobalPooledServlet
in Listing 7.11.
L
ISTING
7.11
TitleListGlobalPooledServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import ConnectionPool.*;
public class TitleListGlobalPooledServlet extends HttpServlet {
public void init(ServletConfig config)
throws ServletException {
super.init(config);
}