【发布时间】:2018-03-28 22:56:57
【问题描述】:
我已经用 Eclipse 创建了一个 Web 项目,以便在 Tomcat v7 上运行我的 Web 服务。我有一个配置文件,它必须定义一些变量,这些变量应该在网络服务器启动时更改,而无需重新启动它。问题是:我可以把这个文件放在哪里? 目前我已将其放入“./”目录,但似乎当我导出 WAR 文件并将其安装在网络服务器上时它不起作用。有没有办法在 WAR 中创建这个文件并在运行时修改它?
这是访问配置文件的.class文件的部分代码
public class ToolConfigurations {
private static final Logger log = LogManager.getLogger(ToolConfigurations.class); //Oggetto logging
private static ToolConfigurations instance = null; //verificarne la necessità
private static String defaultServerName = null;
private static String defaultDbName = "postgres";
private static String defaultDbUser = "postgres";
private static String defaultDbPass = "password";
private static int defaultDbMaxConnNum = 10;
private static String configFilePath = ".\\";
private static String configFileName = "tool.properties";
private String serverName = null;
private String dbName = null;
private String dbUser = null;
private String d`enter code here`bPass = null;
private int dbMaxConnNum = -1;
private ToolConfigurations() throws Exception {
File file = new File(configFilePath + configFileName);
if(file.exists()) {
//file configurazione esiste
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String line = null;
while((line = br.readLine()) != null) { //Leggo riga per riga il file
String[] values = line.split(" ");
switch (values[0]) {
case "serverName":
serverName = values[1];
break;
case "dbName":
dbName = values[1];
break;
case "dbUser":
dbUser = values[1];
break;
case "dbPass":
dbPass = values[1];
break;
case "dbMaxConnNum":
dbMaxConnNum = Integer.parseInt(values[1]);
break;
default:
log.warn("Elemento inaspettato nel file di configurazione: " + values[0]);
break;
}
}
br.close();
in.close();
}else {
if(file.createNewFile() == false) {
//Errore creazione file
log.error("Errore creazione file di configurazione");
throw new Exception("Errore creazione file configurazione");
}
//CREO FILE CONFIGURAZIONE CON IMPOSTAZIONI DI DEFAULT
FileWriter fw = new FileWriter(file);
fw.write("dbName " + defaultDbName + "\r\n");
fw.write("dbUser " + defaultDbUser + "\r\n");
fw.write("dbPass " + defaultDbPass + "\r\n");
fw.write("dbMaxConnNum " + defaultDbMaxConnNum + "\r\n");
fw.flush();
fw.close();
log.warn("File di configurazione non trovato. Path: " + file.getAbsolutePath() + ". Creato nuovo file con configurazioni di default.");
//CARICO IMPOSTAZIONI DI DEFAULT
dbName = defaultDbName;
dbUser = defaultDbUser;
dbPass = defaultDbPass;
dbMaxConnNum = defaultDbMaxConnNum;
}
}
public static synchronized ToolConfigurations getInstance() throws Exception {
if(instance == null) {
instance = new ToolConfigurations();
}
return instance;
}
...
【问题讨论】:
-
WAR 不打算在运行时进行修改。也就是说,您可以操纵爆炸(解压缩)的战争。我建议反对它。您可能会发现将配置放入 JNDI 是一个更好的主意。
-
我需要一个地方来放置和访问我的配置文件,独立于我放入的环境。
标签: java eclipse file tomcat war