Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - Retrieve Init parameters outside servlet

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...