简略版本
配置信息
context.xml配置
存放位置webapp/MET-INF/context.xml
1 2 3 4 5 6 7 8 9 10 11
| <?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/UserPlatformDB" type="javax.sql.DataSource" auth="Container" description="Derby database for User Platform" maxActive="100" maxIdle="30" maxWait="10000" username="" password="" driverClassName="org.apache.derby.jdbc.EmbeddedDriver" url="jdbc:derby:user-platform;create=true"/>
</Context>
|
pom.xml配置
这个配置是嵌入工程tomcat一个插件,需要在开启jndi。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <dependencies> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derby</artifactId> <version>${derby.version}</version> </dependency> </dependencies> <executions> <execution> <id>tomcat-run</id> <goals> <goal>exec-war-only</goal> </goals> <phase>package</phase> <configuration> <path>/</path> <enableNaming>true</enableNaming> </configuration> </execution> </executions> </plugin> </plugins> </build>
|
运行代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| protected Connection getConnection(){ Context context = null; try { context = new InitialContext(); Context envContext = (Context) context.lookup("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup("jdbc/UserPlatformDB"); Connection connection = dataSource.getConnection(); if (connection != null){ System.out.println("获取JNDI 成功!!"); } return connection; } catch (NamingException | SQLException e) { servletContext.log(e.getMessage(), e); throw new RuntimeException(e); }
}
|