在Tomcat配置JNDI数据源

局部配置。
将mysql的jar包导入到:
x:\tomcat\apache-tomcat-8.0.53\lib 下面,需要较新的驱动包

1)在项目的META-INF下面新建context.xml。加入:

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true" crossContext="true">
	<Resource auth="Container"
			  type="javax.sql.DataSource"
			  maxActive="20"
			  maxIdle="10"
			  maxWait="10000"
			  name="jndi/mysql"
			  driverClassName="com.mysql.jdbc.Driver"
			  url="jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8&amp;serverTimezone=GMT"
			  username="root"
			  password="root"/>
</Context>

2)在项目的web.xml中加入资源引用:

 <resource-ref>    
      <description>JNDI DataSource</description>    
      <res-ref-name>jndi/mysql</res-ref-name>    
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>    
    </resource-ref>    

其中res-ref-name值要和context.xml的name值一致。

3)jndi测试方法:

package com.tedu.jndiTest;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;







public class JNDITest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public JNDITest() {
        super();
        
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection conn = null;
		String  jndi  =  "jndi/mysql";     
		Context initContext;
		try {
			initContext = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource)envContext.lookup(jndi);	
			 if(ds !=  null){
				 conn = ds.getConnection();
				 System.out.println(conn.isClosed());
			 }
			 
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
		}
		 
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		doGet(request, response);
	}

}

发布了27 篇原创文章 · 获赞 0 · 访问量 847

猜你喜欢

转载自blog.csdn.net/xiaobao1352/article/details/104406219