在这种情况下,您有很多选择如何初始化常量。有两种常见的方式
1) 初始化参数。
web.xml
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>my.package.MyServlet</servlet-class>
<init-param>
<param-name>myParam</param-name>
<param-value>paramValue</param-value>
</init-param>
</servlet>
MyServlet.java
public class MyServlet extends HttpServlet {
protected String s;
@Override
public void init(ServletConfig servletConfig) throws ServletException{
super(servletConfig);
this.s = servletConfig.getInitParameter("myParam");
}
....
}
2) 配置文件
您应该在您的应用程序中创建属性文件,例如 config.properties 在 src 文件夹中
myParam=paramValue
配置文件
public class Config {
private Properties config;
public Config() {
config = new Properties();
reloadConfig();
}
public Properties getConfig(){
reloadConfig();
return config;
}
public String getProperty(String key){
return getConfig().getProperty(key);
}
public void reloadConfig() {
try {
config.load(getClass().getResourceAsStream("/config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
MyServlet.java
public class MyServlet extends HttpServlet {
protected Config config = new Config();
@Override
public void doGet(request, response) throws ServletException{
Strign s = config.getProperty("myParam");
}
}