java开发——在servlet容器初始化时加载配置文件(.properties)的信息

本文介绍了如何在Java的Servlet容器启动时加载配置文件。通过创建实现ServletContextListener接口的监听器,并在contextInitialized方法中读取.properties文件,然后在web.xml中配置监听器。特别提示,配置时应注意监听器的位置,需位于Spring MVC的DispatcherServlet之前。

主要步骤如下:

1、建一个自己的监听器实现ServletContextListener接口;

2、实现contextInitialized方法,在此方法中加载配置文件信息;

3、在web.xml中配置监听器的信息。

实例代码如下:

public class WebAppEventListener implements ServletContextListener
{
  
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        final ServletContext context = sce.getServletContext();
        String path = context.getRealPath("/");
        MyApplication.initlize(path);
    }
}

public class MyApplication {
    private static String webPath = null;
    private static String xxxxxx;

    public static void initlize(String webPath) {
        MyApplication.webPath = webPath;
        //app.properties放在resource根目录下
        InputStream is = MyApplication.class.getClassLoader().getResourceAsStream("app.properties");
        if (is == null) {
            return;
        }
        Properties p = new Properties();
        p.load(is);
        is.close();
        xxxxxxx = p.getProperty("xxxx.xxx.xxxx");
    }

 我们知道spring mvc的核心控制器是一个servlet(DispatcherServlet),所以我们配置的servlet监听器要记得放在springmvc前面哦!

<listener>
      <listener-class>com.xxxx.xxx.xx.WebAppEventListener</listener-class>
</listener>

 <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        ...
</servlet>

 如果对您有用的话赞一下呗!谢谢啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值