If the location of the config is known, you can pass it as a servlet parameter. In your web.xml
where you declare your servlet (I refer to configFile as the file you wish to get a reference to):
<servlet>
<servlet-name>ConfigParser</servlet-name>
<servlet-class>foo.baar.ConfigParser</servlet-class>
<init-param>
<param-name>configFilePath</param-name>
<param-value>/path/to/the/config/file</param-value>
</init-param>
</servlet>
I guess you know where the web.xml
file is because you are already using servlet.
Then in your servlet, you can you ServletConfig.getInitParameter("configFilePath")
to get the location of the config file. e.g. in your servlet:
public void init(ServletConfig config) throws ServletException {
super.init(config);
String path_to_config_file=config.getInitParameter("configFilePath");
}
Container will call this method with the ServletConfig
where you get your reference to the config file.
That means, you are not required to have that file in eclipse at all. With this approach, you don't have to do anything special on your server, the only thing to take care of is that the file is copied over and the path you declare on your web.xml
is correct.
If the location of the file can be constructed dynamically, you can use ServletContext.getRealPath("/") that returns the absolute path of the webapp.
---UPDATE---
Answer to the updated question. I don't know what is the best practice to do it, but there is a workaround. You create a file (conf_location.txt
) in the tomcat home directory which contains one line with the location of the file you want to pass to the servlet. In your servlet, you can get access to the file with this hack (given your war is in $TOMCAT_HOME/webapps/mywar.war
):
public void init() throws ServletException{
String contextPath=getServletContext().getRealPath("/");
File tomcatHome=new File(contextPath).getParentFile().getParentFile();
File configFile=new File(tomcatHome,"conf_location.txt");
try {
String config_location = new Scanner(configFile).useDelimiter("\\Z").next();
} catch (Exception e) {}
}