Preface:
Because in the learning process, the tutorial is carried out using eplices, and I am using idea, so the configuration process is recorded
Operating environment: OS X 10, Idea Community Edition, Java8, MySQL 5.1.38, tomcat7-maven-plugin steps:
Create the context.xml in the Web-inf folder of the Web project, as follows
<!--context.xml-->
<?xml version= "1.0" encoding= ' UTF-8 '?>
<context>
< watchedresource>web-inf/web.xml</watchedresouurce>
<resource name= "jdbc/msg"
auto= " Container "
type=" Javax.sql.DataSource "
username=" "Root"
password= "hh13532550193!"
Driverclassname= "Com.mysql.jdbc.Driver"
maxactive= "maxidle="
/>
</context>
Add the path to the context.xml file in the TOMCAT7 dependency configuration in the project's Pom.xml file so that TOMCAT7 can refer to the file correctly:
<!--pom.xml -->
<build>
<plugins>
<plugin>
<groupId> Org.apache.tomcat.maven</groupid> .....
....
<configuration> ...
<contextfile>context.xml file path </contextFile>
</configuration>
....
</plugin>
</plugins>
</build>
Declare in Web.xml
<!--web.xml-->
<resource-ref>
<res-ref-name>jdbc/msg</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
To get a database link in Java code:
import javax.naming.Context; import javax.naming.InitialContext; import
Javax.sql.DataSource;
Import java.sql.*;
.....
Context Initctx = new InitialContext ();
Context Envctx = (context) initctx.lookup ("java:comp/env");
DataSource ds = (DataSource) envctx.lookup ("jdbc/msg"); Connection conn = Ds.getconnection ();