0
我知道有一個名爲web.xml的配置文件 我想實現的是另一個具有應用程序特定配置的配置文件,它必須在Web服務器啓動時讀取。我也希望一個類能夠讀取這個配置。有沒有一種方法可以配置這是web.xml文件本身還是有另一種方式如何在eclipse動態web項目中讀取配置文件?
我知道有一個名爲web.xml的配置文件 我想實現的是另一個具有應用程序特定配置的配置文件,它必須在Web服務器啓動時讀取。我也希望一個類能夠讀取這個配置。有沒有一種方法可以配置這是web.xml文件本身還是有另一種方式如何在eclipse動態web項目中讀取配置文件?
您可以使用Apache Commons配置。看看user guide。既然你希望它在啓動時完成這裏是一個樣本的ServletContextListener:
package test;
import java.io.File;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
public class ConfigurationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
File configFile;
try {
configFile = new File(context.getResource("/WEB-INF/configuration.xml").getPath());
Configuration config = new XMLConfiguration(configFile);
context.setAttribute("configuration", config);
} catch (ConfigurationException | MalformedURLException ex) {
Logger.getLogger(ConfigurationListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {}
}
現在把你的配置在Web應用程序中像這樣:
Configuration config = (Configuration) request.getServletContext().getAttribute("configuration");
我將創建一個類來保存配置儘管不是將它作爲一個屬性添加到ServletContext中。該類僅通過靜態方法提供對配置的訪問。
我做了以下操作來訪問我加載的xml文件: configFile = new File(context.getResource(「/ WEB-INF/academy.xml」).getPath()); \t \t \t Configuration config = new XMLConfiguration(configFile); System.out.println(「根元素名稱:」+ config.getString(「application.name」)); 該語句返回null。我的xml結構是:學院 application> –