0

How to read the values from properties file in java script?

I goggling about it but not satisfied.Please share me some samples or links. My application develops by jsp-servlet, eclipse LUNA and Windows7.

SK.
  • 4,174
  • 4
  • 30
  • 48
Bhoomi Akhani
  • 25
  • 1
  • 5

2 Answers2

1

You can read property file in many way, below is one of the way. Good Link

config.properties

dbpassword=password
database=localhost
dbuser=mkyong

App.java

package com.mkyong.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class App {
  public static void main(String[] args) {

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("config.properties");

    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}
}

Google Links

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48
1

Javascript is executed on the client side and cannot access local files (except the html5 web storage).

If you want to access properties which are defined in a properties file on the server side you have two options:

Server side parsing

Read the properties file at the server side and write the values to the html response as JS values

// output a property as JS value to the client. Make sure this is inside a 
// <script> tag
void printProperty(Properties properties, String key) {
   Sytem.out.println("var " + key + "='"properties.getProperty("key") + "'");
}

Client side parsing (more complex)

  1. Make the properties file available through an URL (http:/.../conf.properties)
  2. Read the file via ajax
  3. Parse the properties file
davidgiga1993
  • 2,695
  • 18
  • 30