当然,您不能在网络应用中存储硬编码凭据。
因此,您必须将它们存储在外部,在您部署的服务器上。
在特定容器功能(如数据源)之外,您可以:
1) 使用 java Preferences,但是它们有很多错误,特别是如果在 linux 上使用 tomcat,我不会考虑它们(我做了,我清理了)
2) 将连接属性放在外部文件中。这是我的做法:
我的 WEB-INF 目录中有一个文本文件,列出了这些属性的所有授权位置。此文件按原样部署在所有服务器上。这是一个例子:
# This file lists all the locations where mysoft will look for
# an XML config file when starting.
# It's recommended to use links to simplify parameterization but
# it's also possible to enrich this file.
# standard windows locations
c:\mycomp\mysoft\config\config.xml
d:\mycomp\mysoft\config\config.xml
# standard linux location
/var/lib/mycomp/mysoft/config/config.xml
我的 webapp 在初始化时只是选择了第一个找到的文件。
为此,我实现了一个 ServletContextListener,我在其中读取文本文件并存储配置。
这是我的听众的一个非常简化的版本:
public class MySoftServletContextListener implements ServletContextListener {
public final static String CONFIG_LIST_PATH = "/WEB-INF/config-paths.txt";
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
InputStream list = context.getResourceAsStream(WORLD_LIST_PATH);
try {
BufferedReader listReader = new BufferedReader(new InputStreamReader(list));
String line;
while ((line=listReader.readLine())!=null) {
if (line.length()<4 || line.charAt(0)=='#') continue;
File file = new File(line);
if (file.exists()) {
// log config from the file and, for example, store it in a singleton
break;
} else {
log.info("No config in file " + line + " (file doesn't exist)");
}
}
list.close();
} catch (IOException e) {
e.printStackTrace();
log.severe("Error while looking for a config : " + e.toString());
}
}
}
servlet 上下文侦听器在我的 web.xml 中被引用,如下所示:
<listener>
<listener-class>com.mycomp.mysoft.webapp.MySoftServletContextListener</listener-class>
</listener>