简体   繁体   中英

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

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"));

check all names. your code is working fine.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM