gpt4 book ai didi

java - context.xml的解释

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:10 25 4
gpt4 key购买 nike

使用 Tomcat 时,我一直将 web.xml 视为一种 .htaccesshttpd.conf 等同物。似乎很自然,可能必须有某种配置 Web 服务器的方法。

不过,我不太明白context.xml的用途。例如,在使用 JDBC 时,为什么我必须在 web.xml 中添加一个 resource-ref 以及一个包含更多内容的 Resource context.xml 中的信息?我可以删除 context.xml 文件并以某种方式在我的代码中实例化 DataSource 吗?我问是因为这样的假设性例子可以帮助我理解。

编辑:我试图了解在这样的配置中发生了什么,在 /META-INF/context.xml 中:

<Context>
<Resource name="jdbc/postgres" auth="Container" type="javax.sql.DataSource"
driverClassName="org.postgresql.Driver" url="jdbc:postgresql://127.0.0.1:5432"
username="postgres" password="yes" maxActive="20" maxIdle="10"
maxWait="-1" />
</Context>

并且,在 WEB-INF/web.xml 中:

<resource-ref>
<description>postgreSQL Datasource example</description>
<res-ref-name>jdbc/postgres</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

为什么我必须把它们都放在那里才能使用 JDBC?他们到底在做什么,除了在 Java 代码中,还有另一种方法可以做同样的事情吗?就像我说的,不是因为我想,而是因为我想更好地了解他们在哪些方面做得更好。

最佳答案

I don't quite understand the purpose of context.xml

context.xmlweb.xml 调用通过<context-param>标签。 当您创建应用程序时首先加载 web.xml,它将为 contexts 创建引用在其中配置

I don't quite understand the purpose of context.xml

因此,context.xml 的目的正在添加代码分离。您可以为不同的目的使用单独的上下文。例如对于数据库连接,使用其他框架等。

Could I eliminate the context.xml file and somehow instantiate the DataSource in my code?

是的,您可以通过配置 datasource 来做到这一点在 web.xml本身。

希望对您有所帮助!!

关于java - context.xml的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147836/

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