tomcat中配置jndi数据库源

tomcat添加依赖

lib目录下添加依赖mysql-connector-java-8.0.16

配置数据源

介绍两种方法:tomcat中配置或web应用中配置

tomcat/conf/context.xml配置

<Context>
    <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
	driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/test2?serverTimezone=UTC"
	username="root" password="123456"  maxActive="20" maxIdle="10" 
          maxWait="-1"
/>
</Context>

web应用中配置

建立META-INF/context.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
          driverClassName="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/test2?serverTimezone=UTC"
          username="root" password="123456"  maxActive="20" maxIdle="10"
          maxWait="-1"
/>
</Context>

测试

编写监听器,web项目启动时输出数据源信息

@WebListener
public class WebContextListener implements ServletContextListener {
//web应用是可以使用java:comp/env
@Resource(lookup = "java:comp/env",name = "jdbc/mysql")
private DataSource dataSource;

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {
        System.out.println(dataSource.getConnection());
    }catch (Exception e){
        e.printStackTrace();
    }
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}

输出内容:543123604, URL=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC, UserName=root@localhost, MySQL Connector/J

posted @ 2019-07-16 17:16  远去的列车  阅读(430)  评论(0编辑  收藏  举报