Advertisement
uopspop

Untitled

Oct 7th, 2016
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package connectionPool;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.sql.Connection;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.ArrayList;
  9.  
  10. import javax.servlet.ServletContext;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.UnavailableException;
  13. import javax.servlet.http.HttpServlet;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16.  
  17. import javax.servlet.annotation.*;
  18.  
  19. @WebServlet("/ConnContext")
  20. public class ConnContext extends HttpServlet {
  21.  
  22.     public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  23.         res.setContentType("text/html; charset=UTF-8");
  24.         PrintWriter out = res.getWriter();
  25.  
  26.         // get/set connection pool and put it in Context object
  27.         ServletContext context = req.getServletContext();
  28.         ConnectionPool connPool = (ConnectionPool) context.getAttribute("connList");
  29.         if (connPool == null) {
  30.             System.out.println("Create connection pool.");
  31.             connPool = new ConnectionPool();
  32.             connPool.openDB(2);
  33.             context.setAttribute("connList", connPool);
  34.         }
  35.  
  36.         // get connection from connection pool:
  37.         Connection con = connPool.getConnection();
  38.         System.out.println("After getConnection() connList: " + connPool.size());
  39.  
  40.         // make current Thread wait for testing purpose
  41.         try {
  42.             Thread.sleep(10000); // 象徵意義:這個人在查資料,且用了好久,占掉一個Connection物件資源
  43.         } catch (InterruptedException e) {
  44.             e.printStackTrace();
  45.         }
  46.         // get data via sql commands
  47.         out.println(new HtmlSQLResult("SELECT * from emp2", con));
  48.  
  49.         // return connection back to connection pool:
  50.         connPool.returnConnection(con);
  51.         System.out.println("After returnConnection() connList: " + connPool.size());
  52.  
  53.         // wrap up the results
  54.         context.setAttribute("connList", connPool);
  55.     }
  56.    
  57.     @Override
  58.     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  59.         ServletContext context = req.getServletContext();
  60.         ConnectionPool connPool = (ConnectionPool) context.getAttribute("connList");
  61.         connPool.closeDB();
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement