2

I have a 3-tier application I have to modify. I'm totally new to the entire webstuff of Java, so bear with me please.

Currently the application has a UI, Application and Database layer but I am attempting to decouple the SQL database from the database layer using dependency injection.

So at some point I'm not going to need SQL server credentials in my application because the database backend might be plain text.

The point is that the current SQL credentials are stored in the web.xml file as init-parameters. These are fetched in servlet code as follows:

String cfgfile = getInitParameter("config_file");
properties.load(new FileInputStream(cfgfile));
//Some code..
properties.getProperty("dbUser");

This happens in the front-end, is passed to the applicationlayer constructor, which passes it on to the database constructor.

So this works, but the credentials are just passed along to the data access layer to then create a SQLDatabase.

So I figured I'd just pull these credentials in inside the SQL specific class. However, I'm stuck on how to get them out of the web.xml file.

I tried using getServletContext() but that doesnt seem to work.

I can imagine that there is no notion of any servlet at the DAL level, so I'm stuck on how to fix this.

2
  • What framework are you using? Spring? Commented Mar 8, 2014 at 13:05
  • Indeed, I am using Spring. Commented Mar 8, 2014 at 13:09

2 Answers 2

3

Register ServletContextListener to load Init parameters at server start-up.

Load properties and make it visible to other classes statically.

Sample code:

public class AppServletContextListener implements ServletContextListener {
    private static Properties properties;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String cfgfile = servletContextEvent.getServletContext().getInitParameter("config_file");
        properties.load(new FileInputStream(cfgfile));
        //Some code..
        properties.getProperty("dbUser");
    }

    public static Properties getProperties(){
        return properties;
    }
}

web.xml:

<listener>
    <listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>

<context-param>
      <param-name>config_file</param-name>
      <param-value>config_file_location</param-value>
</context-param>
1

You are correct that the web.xml seems the wrong place to be defining database credentials.

It sounds like you really want to define the database credentials as properties and inject them directly into your data access layer.

As you are using Spring you might want to consider defining a DataSource within your context.xml and either defining the credentials directly in there or using a properties file. Have a look at the Spring documentation for more details.

Not the answer you're looking for? Browse other questions tagged or ask your own question.