在servlet外部检索Init参数 [英] Retrieve Init parameters outside servlet

查看:86
本文介绍了在servlet外部检索Init参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

目前应用程序有一个UI,应用程序和数据库层,但我试图解耦来自数据库层的SQL数据库使用依赖注入。

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.

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

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

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

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.

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

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

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

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.

我尝试使用 getServletContext()但这似乎不起作用。

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

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

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

推荐答案

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

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

加载属性并静态显示其他类。

Load properties and make it visible to other classes statically.

示例代码:

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>

这篇关于在servlet外部检索Init参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆