【问题标题】:Connect to Datasource without resource-ref in web.xml在 web.xml 中连接到没有资源引用的数据源
【发布时间】:2013-08-03 00:09:16
【问题描述】:
我有一个在 tomcat7 上运行的 Web 应用程序。 tomcat7 和全局数据源配置组件是码头门户的一部分。现在,我可以在门户上设置全局数据源,这些数据源作为 ResourceLink 添加到 context.xml(我在 tomcat 上的应用程序)。我想知道是否有一种方法可以通过我的应用程序 jdbc 代码连接到这些数据源,而无需在我的 web.xml 中放入资源引用。
(这将帮助我连接到新的数据源名称,而无需重新部署我的 WAR 文件只是为了添加新的资源引用标签)
【问题讨论】:
标签:
java
tomcat
jdbc
datasource
【解决方案1】:
似乎这是按原样工作的。由于我的上下文没有正确刷新,我在完成这项工作时遇到了问题。
重新部署后,ResourceLink 在上下文中正确设置,webapp 能够进行 JNDI 查找并连接到数据源。
【解决方案2】:
如果您使用的是 Apache Tomcat 7,您可以在 servlet 中使用 @Resource 来注入数据源。
在项目本地的META-INF目录中添加文件context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/TestResource">
<Resource name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password=""
url="jdbc:mysql://localhost:3306/test"
maxActive="100"
maxIdle="30"
maxWait="10000"/>
</Context>
在 servlet 中:
@WebServlet(urlPatterns = { "/" }, loadOnStartup = 0)
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource(name = "jdbc/test")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
try (Connection conn = ds.getConnection();
PrintWriter out = resp.getWriter();) {
out.println(conn.getMetaData().getDatabaseProductName());
out.println(conn.getMetaData().getDatabaseProductVersion());
} catch (SQLException e) {
log(e.getMessage(), e);
}
}
}
WAR结构如下:
C:.
+---META-INF
| context.xml
| MANIFEST.MF
|
\---WEB-INF
+---classes
| \---test
| TestServlet.class
|
\---lib
mysql.jar
浏览器中的输出http://localhost:8080/Test/:
MySQL
5.5.32