在servlet外部检索Init参数

时间:2014-03-08 12:59:47

标签: java servlets

我有一个我必须修改的3层应用程序。我对Java的整个网络都是新手,所以请耐心等待。

目前,该应用程序具有UI,应用程序和数据库层,但我试图使用依赖注入将SQL数据库与数据库层分离。

所以在某些时候我不需要在我的应用程序中使用SQL服务器凭据,因为数据库后端可能是纯文本。

关键是当前的SQL凭据作为init-parameters存储在web.xml文件中。这些是在servlet代码中获取的,如下所示:

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

这发生在前端,传递给applicationlayer构造函数,后者将其传递给数据库构造函数。

这样可行,但凭据只是传递给数据访问层,然后创建一个SQLDatabase。

所以我想我只是在SQL特定类中提取这些凭据。但是,我仍然坚持如何将它们从web.xml文件中删除。

我尝试使用getServletContext(),但这似乎无效。

我可以想象在DAL级别没有任何servlet的概念,所以我一直坚持如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

注册 ServletContextListener 以在服务器启动时加载Init参数。

加载属性并使其对其他类静态可见。

示例代码:

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 :(得分:1)

你是正确的,web.xml似乎是定义数据库凭据的错误位置。

听起来你真的想要将数据库凭据定义为属性并将它们直接注入数据访问层。

在使用Spring时,您可能需要考虑在context.xml中定义数据源,并在其中直接定义凭据或使用属性文件。有关详细信息,请查看Spring documentation