如何在GWT中的不同配置之间切换?

时间:2014-03-31 17:38:31

标签: java javascript html gwt

我有一个在开发和生产模式以及网络和移动设备上运行的GWT项目。

我为每种模式都有不同的web.xml文件。

我还需要为每个版本使用不同的常量。目前我用这个:

class Params {

   public static final String SOME_CONSTANT = "value";
   ...
}

SOME_CONSTANT的值可能会在各种模式(应用版本)之间发生变化。

如何为每种模式(dev,prod,web,mobile)设置不同的常量?

1 个答案:

答案 0 :(得分:0)

  

将这些常量移动到每个环境的属性文件中。

创建一个这样的文件夹(它必须在最终生成的war文件之外,服务器上的某个地方)

resources
 |__dev
 |__prod
 |__web
 |__mobile

每个文件夹都包含具有基于环境的值的属性文件。

将服务器启动时的环境值作为系统属性或环境变量传递。在应用程序上下文初始化时加载所有属性,并在应用程序的任何位置使用它。

使用 ServletContextListener 读取服务器启动时的所有属性。

  

如何根据系统属性或环境变量加载属性文件?

使用

 System.getProperty()

System.getenv()

读取属性文件的位置。

并加载属性文件

Properties properties = new Properties()
properties.load(new FileInputStream(new File(absolutePath)));

您可以将属性存储为Application上下文属性,也可以从包括JSP在内的任何位置读取。


- 编辑 -

在服务器启动时加载属性文件:

的web.xml

<listener>
    <listener-class>com.x.y.z.server.AppServletContextListener</listener-class>
</listener>

AppServletContextListener.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AppServletContextListener implements ServletContextListener {

    private static Properties properties = new Properties();

    static {
        // load properties file
        String absolutePath = null;
        if (System.getenv("properties_absolute_path") == null) {
            absolutePath = System.getProperty("properties_absolute_path");
        } else {
            absolutePath = System.getenv("properties_absolute_path");
        }
        try {
            File file = new File(absolutePath);
            properties.load(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().setAttribute("properties", properties);
    }

    public static Properties getProperties() {
        return properties;
    }

}
相关问题