在 web.xml 中定义和初始化变量然后从 Java 代码访问它们的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2434888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:07:36  来源:igfitidea点击:

Best practices for defining and initializing variables in web.xml and then accessing them from Java code

javaconfigurationweb.xml

提问by Chris Dutrow

I would like to define and initialize some variables in web.xml and the access the values of these variables inside my Java application.

我想在 web.xml 中定义和初始化一些变量,并在我的 Java 应用程序中访问这些变量的值。

The reason I want to do this is because I would like to be able to change the values of these variables without having to recompile the code.

我想这样做的原因是因为我希望能够在无需重新编译代码的情况下更改这些变量的值。

What is the best practice for doing this? Most of the variables are just strings, maybe some numbers as well. Does the class that accesses the variables have to be a servlet?

这样做的最佳做法是什么?大多数变量只是字符串,也许还有一些数字。访问变量的类是否必须是 servlet?

Thanks!

谢谢!

Chris

克里斯

回答by Konrad Garus

You could use your own resources, like Properties files, and place them somewhere in the classpath. Then you could read them into Properties and use from wherever you find convenient.

您可以使用自己的资源,如属性文件,并将它们放在类路径中的某个位置。然后您可以将它们读入 Properties 并从您认为方便的任何地方使用。

web.xml is best left for servlet context, not a general purpose resource.

web.xml 最好留给 servlet 上下文,而不是通用资源。

回答by Teja Kantamneni

Why do you want to put those values in web.xml. Web.xml is primarily to configure the application not to set the bootstrap variables. The standard in the java world for such cases is using either a properties file or an xml in case you have some complex data structure.

为什么要将这些值放在 web.xml 中。Web.xml 主要用于配置应用程序不设置引导程序变量。对于这种情况,java 世界中的标准是使用属性文件或 xml,以防您有一些复杂的数据结构。