在Tomcat中配置数据源很简单,但实际做起来确不容易,捣鼓了半天,好不容易才搞定。真实不容易啊!
第一步:
打开tomcat目录下的conf/service.xml文件。在<Host></Host>中加入数据源配置信息:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">

<Context path="/Test" docBase="Test" debug="0" privileged="true" reloadable="true" crossContext="true">
<Resource name="jdbc/mssql" type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" password="123456" maxIdle="2" maxWait="5000" username="tang"
url="jdbc:sqlserver://192.168.1.3:1433;DatabaseName=mydb" maxActive="1000"/>
</Context>
</Host>
第二步:
打开项目中的web.xml文件添加:
<resource-ref>
<res-ref-name>jdbc/mssql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
第三步:
启动Tomcat,在项目中添加测试代码:
public static void initDataSource() {
String dsn = "java:comp/env/jdbc/mssql";
System.out.println("Attempting to connect to " + dsn);

try {
System.out.println("Initializing the naming context...");
InitialContext init = new InitialContext();

System.out.println("Looking up " + dsn);
datasource = (DataSource) init.lookup(dsn);
Connection con = datasource.getConnection();
System.out.println("DataSource initialze successfully!");
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
第一步:
打开tomcat目录下的conf/service.xml文件。在<Host></Host>中加入数据源配置信息:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Context path="/Test" docBase="Test" debug="0" privileged="true" reloadable="true" crossContext="true">
<Resource name="jdbc/mssql" type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" password="123456" maxIdle="2" maxWait="5000" username="tang"
url="jdbc:sqlserver://192.168.1.3:1433;DatabaseName=mydb" maxActive="1000"/>
</Context>
</Host>第二步:
打开项目中的web.xml文件添加:
<resource-ref>
<res-ref-name>jdbc/mssql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>第三步:
启动Tomcat,在项目中添加测试代码:
public static void initDataSource() {
String dsn = "java:comp/env/jdbc/mssql";
System.out.println("Attempting to connect to " + dsn);
try {
System.out.println("Initializing the naming context...");
InitialContext init = new InitialContext();
System.out.println("Looking up " + dsn);
datasource = (DataSource) init.lookup(dsn);
Connection con = datasource.getConnection();
System.out.println("DataSource initialze successfully!");
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
本文详细介绍如何在 Tomcat 中配置 SQL Server 数据源,包括修改 service.xml 和 web.xml 文件的具体步骤,以及通过 Java 代码进行连接测试的方法。

4305

被折叠的 条评论
为什么被折叠?



