1、 在項目中新建context.xml文件,不要在tomcat服務器的目錄中修改context.xml(會對整個服務器生效)。。 在web項目的META-INF中存放context.xml
2、在文件進行配置::: 配置數據庫連接池的技術
1 <?xml version='1.0' encoding='utf-8'?>
2 <Context>
3 <Resource 4 driverClassName="com.mysql.jdbc.Driver" mysql驅動包
5 url="jdbc:mysql://localhost:3306/ssm" 連接
6 username="root" 賬號
7 password="362222" 密碼
8 maxActive="50" 最大連接數量
9 maxIdle="10" 等待連接的數量
10 name="test" 連接池的名稱
11 auth="Container" 誰來管理(Container是tomcat服務器)
12 maxWait="10000" 超過10秒連接不上就報異常
13 type="javax.sql.DataSource" 這是java中專門的為連接數據庫創建的類型
14 />
15 </Context>
3、通過連接池進行連接,獲取連接對象
1 package com.bjsxt.servlet; 2
3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9
10 import javax.naming.Context; 11 import javax.naming.InitialContext; 12 import javax.naming.NamingException; 13 import javax.servlet.ServletException; 14 import javax.servlet.annotation.WebServlet; 15 import javax.servlet.http.HttpServlet; 16 import javax.servlet.http.HttpServletRequest; 17 import javax.servlet.http.HttpServletResponse; 18 import javax.sql.DataSource; 19 @WebServlet("/test") 20 public class DemoServlet extends HttpServlet{ 21 @Override 22 protected void service(HttpServletRequest req, HttpServletResponse resp) 23 throws ServletException, IOException { 24 try { 25 Context cxt=new InitialContext(); Context是上下文接口 context.xml文件對象類型 26 DataSource ds = (DataSource) cxt.lookup("java:comp/env/test");本地數據庫環境 (java:comp/env/這是固定字符串) test是自配置的連接池 27 Connection conn = ds.getConnection(); 25-27行是JNDI代碼 28 PreparedStatement ps=conn.prepareStatement("select * from flower"); 29 resp.setContentType("text/html;charset=utf-8"); 30 ResultSet rs=ps.executeQuery(); 31 PrintWriter out = resp.getWriter(); 32 while(rs.next()){ 33 out.print(rs.getInt(1)+" "+rs.getString(2)); 34 } 35 out.flush(); 36 out.close(); 當關閉連接對象時,把連接對象歸還給數據庫連接池,把狀態改變成idle 37 並不是關閉
38 } catch (NamingException e) { 39 // TODO Auto-generated catch block
40 e.printStackTrace(); 41 } catch (SQLException e) { 42 // TODO Auto-generated catch block
43 e.printStackTrace(); 44 } 45
46 } 47 }