Can't read property file on Server side with GWT

梦想与她 提交于 2019-12-25 04:27:06

问题


I want to read property file on Server side. I have DBConfig.java, useDBConfig.java and DBConfig.properties all placed in server package. I can't read the values from property file on Server Side. Your help is highly appreciated.

public interface DBConfig extends Constants {
@DefaultStringValue("host")
String host(String host);

@DefaultStringValue("port")
String port(String port);

@DefaultStringValue("username")
String username(String username);

@DefaultStringValue("password")
String password(String password);

}


public void useDBConfig() {
DBConfig constants = GWT.create(DBConfig.class);
Window.alert(constants.host());


host = constants.host(host);
port = constants.port(port);
username = constants.username(username);
password = constants.password(password);

}

property file...

host=127.0.0.1
port=3306
username=root
password=root

Thanks in advance.


回答1:


GWT.Create can be used only in client mode. Are you sure that code execute in server side?

If i write in my application GWT.Create in server side i get this error:

java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code! It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.

You can read a properties files in java. The file is similar that Constants files in GWT. Example of Properties file:

key = value host = 127.0.0.1 port = 80 username = guest password = guest

EOF

You can read this file, see the next code:

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

String fileToRead = "MY_PATH"+File.separator+"MY_FILE.properties";
Properties prop = new Properties();
try {
    File propertiesFile = new File(fileToRead);
    prop.load(new FileInputStream(propertiesFile));
    String host = prop.getProperty("host");
    String port = prop.getProperty("port");
    String username = prop.getProperty("username");
    String password = prop.getProperty("password");

    System.out.println(host);
    System.out.println(port);
    System.out.println(username);
    System.out.println(password);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

If the key doesnt exists getProperty(String key) return null. You can use prop.containsKey(String key); to see if the key exists. This function return a boolean (True if exists False in other case).

Greetings



来源:https://stackoverflow.com/questions/25157153/cant-read-property-file-on-server-side-with-gwt

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