How to portably read configuration data from a servlet

耗尽温柔 提交于 2019-11-28 06:58:12

The recommended way to configure an application server for a web application is per JNDI.

Every application server (including Jetty and Tomcat) allows you to configure JNDI parameters.

For Jetty you can add the following to your jetty.xml to add the JNDI parameter param.file:

<!--  JNDI java:comp/env --> 
<New id="param.file" class="org.mortbay.jetty.plus.naming.EnvEntry">
  <Arg>param.file</Arg> 
  <Arg type="java.lang.String"><SystemProperty name="jetty.home" default="."/>etc/config.properties</Arg> 
  <Arg type="boolean">true</Arg> 
</New> 

Then in your servlet you can read the JNDI parameter:

import javax.naming.InitialContext;
import javax.naming.NamingException;

...

public Object readJndi(String paramName) {
  Object jndiValue = null;
  try {
    final InitialContext ic = new InitialContext();
    jndiValue = ic.lookup("java:comp/env/" + paramName);
  } catch (NamingException e) {
    // handle exception
  }
  return jndiValue;
}


public String getConfigPath() {
  return (String) readJndi("param.file");
}

The way to set JNDI values differs for other application servers but the code to read the configuration is always the same.

mhaller

The Servlet init parameters are the right (and standardized) way of defining properties which can be configured by the administrator. Many of the application servers provide a GUI backend where the parameters can be configured.

For an example for Tomcat, see Defining Tomcat servlet context parameters

  • Configure the external location of the properties - either via a jvm argument (when starting the servlet container), or in the web.xml

  • in the external location use config.properties and read it with java.util.Properties

You may take Preferences or hack with user.home, user.dir, etc. But for a few key/value keep things simple.

Write a small Singleton to wrap around Properties and load them from a fix & absolute location

public class LocalConfig extends Properties {

  public static LocalConfig $ = new LocalConfig();

  private LocalConfig() throws IOException {
    load(new File("/etc/myconfig.properties"));
  }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!