gpt4 book ai didi

java - 在 web.xml 中不使用 resource-ref 连接到数据源

转载 作者:行者123 更新时间:2023-11-28 22:35:50 25 4
gpt4 key购买 nike

我有一个在 tomcat7 上运行的 Web 应用程序。 tomcat7 和全局数据源配置组件是 jetty 门户的一部分。现在,我可以在门户网站上设置全局数据源,这些数据源作为 ResourceLink 添加到(我在 tomcat 上的应用程序的)context.xml 中。我想知道是否有一种方法可以通过我的应用程序 jdbc 代码连接到这些数据源,而无需在我的 web.xml 中放入资源引用。

(这将帮助我连接到新的数据源名称,而无需重新部署我的 WAR 文件,只是为了添加新的 resource-ref 标签)

最佳答案

如果您使用的是 Apache Tomcat 7,您可以在 servlet 中使用 @Resource 来注入(inject)数据源。

在项目本地的 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

关于java - 在 web.xml 中不使用 resource-ref 连接到数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com