|
| 1 | +package com.itbulls.learnit.onlinestore.web.servlets; |
| 2 | + |
| 3 | +import jakarta.servlet.http.HttpServlet; |
| 4 | +import java.io.IOException; |
| 5 | +import java.sql.Connection; |
| 6 | +import java.sql.SQLException; |
| 7 | + |
| 8 | +import javax.naming.Context; |
| 9 | +import javax.naming.InitialContext; |
| 10 | +import javax.naming.NamingException; |
| 11 | + |
| 12 | +import javax.sql.DataSource; |
| 13 | + |
| 14 | +import jakarta.annotation.Resource; |
| 15 | +import jakarta.servlet.ServletException; |
| 16 | +import jakarta.servlet.annotation.WebServlet; |
| 17 | +import jakarta.servlet.http.HttpServletRequest; |
| 18 | +import jakarta.servlet.http.HttpServletResponse; |
| 19 | + |
| 20 | +@WebServlet("/cp-demo") |
| 21 | +public class ConnectionPoolDemoServlet extends HttpServlet { |
| 22 | + |
| 23 | + private DataSource ds1; |
| 24 | + |
| 25 | + @Resource(name = "jdbc/connpool") |
| 26 | + private DataSource ds2; |
| 27 | + |
| 28 | + protected void doGet(HttpServletRequest request, HttpServletResponse response) |
| 29 | + throws ServletException, IOException { |
| 30 | + |
| 31 | + InitialContext initialContext; |
| 32 | + try { |
| 33 | + initialContext = new InitialContext(); |
| 34 | + Context context = (Context) initialContext.lookup("java:comp/env"); |
| 35 | + DataSource ds1 = (DataSource) context.lookup("jdbc/connpool"); |
| 36 | + |
| 37 | + Connection conn1 = getConnection(ds1); |
| 38 | + Connection conn2 = getConnection(ds2); |
| 39 | + |
| 40 | + try (conn1; conn2) { |
| 41 | + System.out.println("Connection 1 from DS1:\t" + conn1); |
| 42 | + System.out.println("Connection 2 from DS2:\t" + conn2); |
| 43 | + } |
| 44 | + |
| 45 | + System.out.println("Connection 1 from DS1 after closure:\t" + conn1); |
| 46 | + System.out.println("Connection 2 from DS2 after closure:\t" + conn2); |
| 47 | + |
| 48 | + System.out.println("DS1 equals DS2:\t" + ds1.equals(ds2)); |
| 49 | + } catch (NamingException | SQLException e) { |
| 50 | + e.printStackTrace(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private Connection getConnection(DataSource ds) throws SQLException { |
| 55 | + return ds.getConnection(); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments