在 servlet 外检索初始化参数 [英] Retrieve Init parameters outside servlet

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

问题描述

我有一个需要修改的 3 层应用程序.我对 Java 的整个 web 内容完全陌生,请耐心等待.

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 服务器凭据,因为数据库后端可能是纯文本.

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 凭据作为初始化参数存储在 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 外检索初始化参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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