tomcat配置JNDI
如工程名为fly,在tomcat安装目录下tomcat\conf\Catalina\localhost找到配置文件fly.xml,修改内容:
<Context path="/fly" reloadable="false" docBase="D:\workspace\fly" workDir="D:\workspace\fly\work"> <Resource name="jdbc/MysqlSource" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/fly" username="root" password="1234" driverClassName="com.mysql.jdbc.Driver" maxIdle="3" maxWait="-1" maxActive="50" /></Context>
修改webapp/WEB-INF/web.xml,添加以下内容
<resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/MysqlSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
最后是使用:
try{ Context ctx=(Context) new InitialContext().lookup("java:comp/env"); ds=(DataSource)ctx.lookup("jdbc/MysqlSource") ; conn=this.getConn(); }catch(Exception e){ System.out.println(e.toString()) ; }