JDBC Application advanced in servlet (v)
Last Update:2017-02-27
Source: Internet
Author: User
Now we're going to combine the Dbconnetionmanager and Dbconnectionpool classes to explain the use of connection pools in the servlet:
First, a brief introduction to the lifecycle of the servlet:
The Servlet API defines the servlet lifecycle as follows:
1, the Servlet is created and initialized (init () method).
2, for 0 or more customer calls to provide services (service () method).
3, the servlet is destroyed, memory is reclaimed (Destroy () method).
Examples of using connection pooling in the servlet
The typical performance of a servlet using a connection pool in three phases is:
1. In Init (), call Dbconnectionmanager.getinstance () and save the returned reference in the instance variable.
2. In Sevice (), call getconnection (), perform a series of database operations, and then call Freeconnection () to return the connection.
3. In Destroy (), call Release () to free all resources and close all connections.
The following example shows how to use a connection pool.
Import java.io.*;
Import java.sql.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class Testservlet extends HttpServlet {
Private Dbconnectionmanager connmgr;
public void init (ServletConfig conf) throws Servletexception {
Super.init (conf);
Connmgr = Dbconnectionmanager.getinstance ();
}
public void Service (HttpServletRequest req, httpservletresponse Res)
Throws IOException {
Res.setcontenttype ("text/html");
PrintWriter out = Res.getwriter ();
Connection con = connmgr.getconnection ("IDB");
if (con = = null) {
Out.println ("Cant get connection");
Return
}
ResultSet rs = null;
ResultSetMetaData MD = NULL;
Statement stmt = null;
try {
stmt = Con.createstatement ();
rs = Stmt.executequery ("SELECT * from EMPLOYEE");
md = Rs.getmetadata ();
Out.println ("Employee data");
while (Rs.next ()) {
Out.println ("
");
for (int i = 1; i < Md.getcolumncount (); i++) {
Out.print (rs.getstring (i) + ",");
}
}
Stmt.close ();
Rs.close ();
}
catch (SQLException e) {
E.printstacktrace (out);
}
Connmgr.freeconnection ("IDB", con);
}
public void Destroy () {
Connmgr.release ();
Super.destroy ();
}
}