简体   繁体   English

在 Java 导出的 WAR 中在运行时创建配置文件

[英]Create config file at runtime in Java exported WAR

I've made a web project with eclipse to run my webservice on Tomcat v7.我已经用 Eclipse 制作了一个 web 项目来在 Tomcat v7 上运行我的 web 服务。 I have a config file that have to define some variables that should be changed while webserver is up without need of restart it.我有一个配置文件,它必须定义一些变量,这些变量应该在网络服务器启动时进行更改,而无需重新启动它。 The problem is: where I can put this file?问题是:我可以把这个文件放在哪里? At the moment I've put it into the "./" dir, but seems that when I export the WAR file and install it on the webserver it doesn't works.目前我已将其放入“./”目录,但似乎当我导出 WAR 文件并将其安装在网络服务器上时它不起作用。 Is there a way to create this file and modify it runtime inside the WAR?有没有办法在 WAR 中创建这个文件并在运行时修改它?

Here is part of the code of the .class file that accesses the config file这是访问配置文件的 .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;
    }
    ...

In web server, files other than .class are directly taken in charge by the server.在web服务器中,.class以外的文件由服务器直接负责。 You don't need to reload the server.您不需要重新加载服务器。

But try using .properties files and check the structure of the WAR when deployed on the server.但是尝试使用.properties文件并在部署在服务器上时检查 WAR 的结构。

The best solution I found was to a ClassLoader to search for the config file that I have previously created into the main directory.我找到的最佳解决方案是使用 ClassLoader 搜索我之前在主目录中创建的配置文件。 The example of use is:使用示例如下:

 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream fileInput = classLoader.getResourceAsStream(configFileName); if(fileInput == null){ //File not found }else{ //File found InputStreamReader sr = new InputStreamReader(fileInput); BufferedReader br = new BufferedReader(sr); try { while((line = br.readLine()) != null) { //Read file line by line } }catch (IOException e) { throw new IOException("Error parsing file: " + e.getMessage()); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM