Tomcat6 MySql JDBC数据源配置 [英] Tomcat6 MySql JDBC Datasource configuration

查看:124
本文介绍了Tomcat6 MySql JDBC数据源配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用Spring的依赖注入来获取数据源对象,并在我的DAO中使用它们,但是现在,我必须编写一个没有该依赖的应用程序.

I've always used Spring's dependency injection to get datasource objects and use them in my DAOs, but now, I have to write an app without that.

在Spring中,我可以这样写:

With Spring I can write something like this:

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" />
    <property name="username" value="u" />
    <property name="password" value="p" />
</bean>

但是在没有Spring或其他任何东西的情况下,如何在DAO中使用数据源呢?我仅使用servlet和JSP.性能是非常重要的因素.

But how can I use datasource in my DAOs without Spring or anything? I'm using servlets and JSPs only. Performance is very important factor.

推荐答案

信不信由你,人们在Spring之前编写应用程序,但有些人仍未使用它:)在您的情况下,您可以使用Tomcat连接池(在那里是文档).让我总结一下:

Believe it or not, people were writing applications before Spring and some are still not using it :) In your case, you could use Tomcat connection pool (and there is a complete configuration example for MySQL in the documentation). Let me summarize it:

首先,将驱动程序放入$CATALINA_HOME/lib.

First, put your driver in $CATALINA_HOME/lib.

然后,通过在

在您的web.xml中声明此资源:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

并在您的应用程序中通过JNDI查找获得数据源:

And get the datasource with a JNDI lookup in your application:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

请注意,此类lookup通常用 ServiceLocator (当您无法使用DI容器或框架为您注入它时.

Note that such lookup is usually coded in a ServiceLocator (when you can't have a a DI container or a framework inject it for you).

这篇关于Tomcat6 MySql JDBC数据源配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆