Maexwell
Maexwell

Reputation: 161

Property File doesnt work

I'm trying to find a way, how to use a properties file in my Java Servlet (extends http-servlet). I've tried out to use ClassLoader#getResourceAsStream() and ServletContext#getResourceAsStream(). But whatever I'm doing, nothing works and there is always a NullPointerException.

database.properties File:

Driver=org.postgresql.Driver
Protokoll=jdbc:postgresql://
Speicherort=localhost/
Datenbank=Ticketshop
User=postgres

code:

p = new Properties();
p.load(getServletContext().getResourceAsStream("/WEB-INF/properties/database.properties"));
protokoll = p.getProperty("Protokoll");
speicherort = p.getProperty("Speicherort");
user = p.getProperty("User");
driver = p.getProperty("Driver");
password = p.getProperty("Password");
database = p.getProperty("Datenbank");

file-tree:

Java Resources
  |-- src
     |-- login
        |-- Login.java
WebContent
  |-- WEB-INF
     |-- properties
        |-- database.properties

Upvotes: 1

Views: 783

Answers (4)

Sudhakar
Sudhakar

Reputation: 4873

Try this

Edit

p.load(getServletContext().getClassLoader().getResourceAsStream("properties/database.properties"));

And BTW you need to move the database.properties to /WEB-INF/classes folder for this to work

The Folder structure should be

WEB-INF
  | classes
      |properties
       database.properties

Upvotes: 1

neonleo
neonleo

Reputation: 192

check all names. your code is working fine.

Upvotes: 1

markosca
markosca

Reputation: 136

I agree with "dj aqeel" but to get a ResourceBundle, this must be in the class directory.

Thus, I put the file in "/WEB-INF/classes/properties/database.properties". Obviously, you must put the file in the src directory and the compiler move there automatically.

Marcos

Upvotes: 0

user517491
user517491

Reputation:

Why don't you use ResourceBundle. It is so simple to use. Place properties file in the source folder, and

import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class DatabaseConstantsAccessor
{
    // don't include .properties extension, just specify the name without extension
    private static final String BUNDLE_NAME = "database";

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    private ConstantsAccessor()
    {
    }

    public static String getString(String key)
    {
        try
        {
            return RESOURCE_BUNDLE.getString(key);
        }
        catch (MissingResourceException e)
        {
            return '!' + key + '!';
        }
    }
}

And where you want to access properties, use following code:

String driverString=DatabaseConstantsAccessor.getString("Driver");
Integer intProp=Integer.valueOf(DatabaseConstantsAccessor.getString("SomeIntProperty"));

Upvotes: 2

Related Questions