Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package connectionPool;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.UnavailableException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.annotation.*;
- @WebServlet("/ConnContext")
- public class ConnContext extends HttpServlet {
- public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
- res.setContentType("text/html; charset=UTF-8");
- PrintWriter out = res.getWriter();
- // get/set connection pool and put it in Context object
- ServletContext context = req.getServletContext();
- ConnectionPool connPool = (ConnectionPool) context.getAttribute("connList");
- if (connPool == null) {
- System.out.println("Create connection pool.");
- connPool = new ConnectionPool();
- connPool.openDB(2);
- context.setAttribute("connList", connPool);
- }
- // get connection from connection pool:
- Connection con = connPool.getConnection();
- System.out.println("After getConnection() connList: " + connPool.size());
- // make current Thread wait for testing purpose
- try {
- Thread.sleep(10000); // 象徵意義:這個人在查資料,且用了好久,占掉一個Connection物件資源
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // get data via sql commands
- out.println(new HtmlSQLResult("SELECT * from emp2", con));
- // return connection back to connection pool:
- connPool.returnConnection(con);
- System.out.println("After returnConnection() connList: " + connPool.size());
- // wrap up the results
- context.setAttribute("connList", connPool);
- }
- @Override
- protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- ServletContext context = req.getServletContext();
- ConnectionPool connPool = (ConnectionPool) context.getAttribute("connList");
- connPool.closeDB();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement