一个数据库连接池的例子,可能对你有帮助:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;public class ConnectionPoolServlet extends HttpServlet{

//初始化全局变量
public void init (ServletConfig config)
throws ServletException{
super.init(config);

ConnectionPool pool=new ConnectionPool();

try{
pool.setDriver("com.microsoft.jdbc.sqlserver.SQLServerDriver");

pool.setURL("jdbc:microsoft:sqlserver://192.168.0.208:1433;DataBaseName=pubs");

pool.setUsername("sa");

pool.setPassword("");

pool.initializePool();

//一旦连接池初始化后,把它加入全局变量 ServletContext中
//这使得其他Servlet都可以使用它
ServletContext context=getServletContext();

context.setAttribute("CONNECTION_POOL",pool);

}
catch (Exception e){
System.err.println(e.getMessage());
}
}

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out =response.getWriter();
out.println("This Servlet does not service requests!");

out.close();

}
public void destroy(){

ServletContext context=getServletContext();

ConnectionPool pool=(ConnectionPool)context.getAttribute("CONNECTION_POOL");

if(pool!=null){
pool.emptyPool();
context.removeAttribute("CONNECTION_POOL");

}
else{
System.err.println("Can't get a reference to pool!");
}
}public String getServletInfo(){
return "ConnectionPoolServlet information!";
}

}

解决方案 »

  1.   

    上面例子就是把一个连接池对象ConnectionPool加入全局变量给所有Servlet用的例子,主要是:
    ServletContext context=getServletContext();

    context.setAttribute("CONNECTION_POOL",pool);其他Servlet就可以直接引用了
      

  2.   

    我感觉你说的是不是javabean的scope的问题,scope="application"的时候,这个bean就是全局的,当然在需要使用的地方还要usebean一下。