Apaachee
Apaachee

Reputation: 900

Servlet init and Class

I actually have a programm with a servlet :

@WebServlet("/Controler")
public class Controler extends HttpServlet {

}

I need to use a property file : file.properties in my program. To load it, I have a class :

public class PropLoader {

    private final static String m_propertyFileName = "file.properties";

    public static String getProperty(String a_key){

        String l_value = "";

        Properties l_properties = new Properties();
        FileInputStream l_input;
        try {

            l_input = new FileInputStream(m_propertyFileName); // File not found exception
            l_properties.load(l_input);

            l_value = l_properties.getProperty(a_key);

            l_input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return l_value;

    }

}

My property file is in the WebContent folder, and I can access it with :

String path = getServletContext().getRealPath("/file.properties");

But I can't call theses methods in another class than the servlet...

How can I access to my property file in the PropLoader class ?

Upvotes: 1

Views: 809

Answers (2)

JB Nizet
JB Nizet

Reputation: 691735

If you want to read the file from within the webapp structure, then you should use ServletContext.getResourceAsStream(). And of course, since you load it from the webapp, you need a reference to the object representing the webapp: ServletContext. You can get such a reference by overriding init() in your servlet, calling getServletConfig().getServletContext(), and pass the servlet context to the method loading the file:

@WebServlet("/Controler")
public class Controler extends HttpServlet {
    private Properties properties;

    @Override
    public void init() {
        properties = PropLoader.load(getServletConfig().getServletContext());
    }
}

public class PropLoader {

    private final static String FILE_PATH = "/file.properties";

    public static Properties load(ServletContext context) {
        Properties properties = new Properties();
        properties.load(context.getResourceAsStream(FILE_PATH));
        return properties;
    }
}    

Note that some exceptions must be handled.

Another solution would be to put the file under WEB-INF/classes in the deployed webapp, and use the ClassLoader to load the file: getClass().getResourceAsStream("/file.properties"). This way, you don't need a reference to ServletContext.

Upvotes: 2

lcestari
lcestari

Reputation: 178

I would recommend to use the getResourceAsStream method (example below). It would need that the properties file be at the WAR classpath.

InputStream in = YourServlet.class.getClassLoader().getResourceAsStream(path_and_name);

Regards Luan

Upvotes: 1

Related Questions