Luis Alves
Luis Alves

Reputation: 1286

Load a properties file in a servlet

I have a properties file in the WEB-INF with some properties that need to be used by my servlet (properties like a database password,...). What's the best way to load this file? Should I Override the init method of the servlet so that I only load the file once?

Thanks

Upvotes: 0

Views: 743

Answers (1)

Pshemo
Pshemo

Reputation: 124215

I am not saying that this way is correct or anything since I don't work with JEE but from what I remember you can use ServletContextListener methods for this. Just implement it like

class ContextListenerImpl implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //lets skip it for now
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ServletContext sc = sce.getServletContext();

        //read parameter from properties and add it to servlet context attributes
        sc.setAttribute("yourParameterName", "value");
    }

}

You should be able to use it in any servlet via for instance

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    //...
    getServletContext().getAttribute("yourParameterName");
    //...
}

BTW value of attributes can hold also other objects, not only Strings.

Oh, and lets not forget to add this listener to your web application. Just add

<listener>
    <listener-class>full.name.of.ContextListenerImpl</listener-class>
</listener>

to your web.xml file.

Upvotes: 1

Related Questions