在 Java (Servlet) 中将应用程序范围的设置放在哪里?
在 ASP.NET 中,有一个 web.config
可以保存应用程序范围的设置。 Java EE Servlet 是否有相应的文件(位于 war
或 jar
存档之外)?
我需要的是在某个地方指出一个配置文件,该文件当前包含四个属性,这些属性组合在一起,会导致存储其余数据和配置的数据库。 (服务器、数据库、用户名和密码。)这些值需要易于更改,而无需重新打包和重新部署整个应用程序(即配置文件),而是将路径硬编码到应用程序中的配置文件(即使它是常量) )似乎远非最佳。
有什么提示吗?我尝试过谷歌,但发现几乎没有相关的内容 - 而且我发现的内容似乎针对我的需求过度设计了。
In ASP.NET, there is web.config
which can hold application-wide settings. Is there a corresponding file (residing outside of the war
or jar
archive) for a Java EE Servlet?
What I need is some place to point out a configuration file, which currently holds four attributes which in turn, taken together, leads to the database where the rest of the data and configuration is stored. (Server, database, username and password.) These values need to be easy to change without repackaging and redeploying the entire application, hence the configuration file, but hardcoding the path to the configuration file in the application (even if it is as a constant) seems far from optimal.
Any hints? I've tried Google but found very little that seemed relevant - and what I did find appeared hideously over-engineered for my needs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是
web.xml
。您可以将设置定义为
条目。它可以通过
ServletContext#getInitParameter( )
。 ServletContext 又可以在任何地方使用。您也可以通过 EL 访问它。
根据重点,我会使用 properties 文件用于此特定目的,然后将其放置在 WAR 之外的路径中。您只需将此路径添加到 Java 运行时类路径即可。然后您可以将其作为类路径资源获取:
但是,由于特定的唯一目的是提供数据库连接,因此您确实最好使用 servletcontainer 管理的数据源,如 Qwerky 所回答的。您可能需要配置的只是数据源名称。
That's the
web.xml
. You can define settings as<context-param>
entries.It's available by
ServletContext#getInitParameter()
. TheServletContext
is in turn available anywhere.You can also access it by EL.
As per the emphasis, I'd use a properties file for this particular purpose which is then placed in a path outside the WAR. You just need to add this path to the Java runtime classpath. Then you can obtain it as classpath resource:
However, with the particular sole purpose to serve a DB connection, you're indeed better off with a servletcontainer-managed datasource as answered by Qwerky. All you possibly would need to configure is then just the datasource name.
如果这是一个 Web 应用程序,那么您最好将数据库连接配置为服务器上的资源,然后让您的应用程序使用 JNDI 检索它。您的应用程序服务器将有有关如何执行此操作的文档,这是一项基本任务。
99% 的严肃网络应用程序都会这样做,另外 1% 应该这么做。
If this is a web app then you'd be better served configuring the database connection as a resource on the server, then getting your app to retrieve it using JNDI. Your app server will have documentation on how to do this, its a basic task.
99% of serious web apps do this, the other 1% should.
您只需将路径作为命令行参数(传递到 servlet 容器启动脚本)即可让应用程序加载任意外部文件。然后将值存储在 ServletContext 中
You can have your application load an arbitrary external file by simply passing the path as a command-line parameter (to the servlet container startup script). Then store the values in the
ServletContext