监听tomcat服务器启动/关闭并从配置文件中读取参数进行初始化

监听tomcat服务器启动/关闭很简单(2步):

1. 建立一个类实现ServletContextListener接口,重写其中的方法(contextDestroyed和contextInitialized)。

复制代码
package action;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SystemListener implements ServletContextListener{
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }
}
复制代码

2. 在web.xml中注册该监听器。如下:

<listener>
      <description>监听tomcat</description>
      <display-name>test</display-name>
      <listener-class>listener.SystemListener</listener-class>
</listener>

监听tomcat启动和关闭就这么简单地完成了。可以把一些tomcat启动时就需要初始化的属性和需要完成的操作放到这步来完成。

下面是完整的项目代码:

1. 目录结构

2. 监听类

复制代码
package listener;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import pub.SystemProperty;

/**
 * 系统上下文启动/关闭监听
 * 把需要初始化的数据放在contextInitialized方法里
 * 
 * @author Sky
 * @date 2016年8月10日 上午9:32:09 listener
 */
public class SystemListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("tomcat关闭了...");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("tomcat启动了...");

        /**
         * 读取系统运行基本参数
         * 读取静态参数
         */
        InputStream input = null;
        try {
            input = SystemListener.class.getClassLoader().getResourceAsStream(
                    "sqlProperty.properties");
            Properties p = new Properties();
            p.load(input);

            String sqlPort = p.getProperty("port", "3306");
            SystemProperty.port = (sqlPort == null || "".equals(sqlPort)) ? 3306
                    : Integer.parseInt(sqlPort);
            SystemProperty.password = p.getProperty("password");

            System.out.println("系统初始化成功");

        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("系统配置文件SystemProperty.properties不存在或读取错误");
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 读取时间配置
         * 读取其他配置文件,并把配置文件的数据加入静态容器中,以便通过类名取出使用
         */
        input = null;
        try {
            input = SystemListener.class.getClassLoader().getResourceAsStream(
                    "timeProperty.properties");
            Properties p = new Properties();
            p.load(input);
            //列举
            Enumeration<?> propNames = p.propertyNames();
            while (propNames.hasMoreElements()) {
                String key = (String) propNames.nextElement();
                String value = p.getProperty(key, "");
                SystemProperty.propList.put(key, value); //放入静态容器中
            }

            System.out.println("时间配置初始化成功");

        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("时间配置文件timeProperty.properties不存在或读取错误");
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
复制代码

3. struts.xml

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <package name="abc" namespace="/" extends="struts-default">
        <action name="test" class="action.TestAction">
            <result name="input">/index.jsp</result>
            <result name="success">/success.jsp</result>
            <result name="fail">/fail.jsp</result>
        </action>
    </package>
</struts>    
复制代码

3. web.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <listener> <description>监听tomcat</description> <display-name>test</display-name> <listener-class>listener.SystemListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
复制代码

4. 静态属性、容器类(方便使用类名直接调用)

复制代码
package pub;

import java.util.HashMap;
import java.util.Map;

/**
 *  静态存储系统运行所需的基本参数,在启动的时候被初始化
 * 
 * @author Sky
 * @date 2016年8月10日 上午10:19:12
 * pub
 */
public class SystemProperty {
    /*
     * 设置为静态,直接使用类名调用
     */
    public static int port; //端口号
    public static String password; //密码
    //静态容器,用来存储后面扩展添加的配置(添加其他的配置文件,使得本类来调用)
    public static Map<String, String> propList = new HashMap<String, String>();
}
复制代码

5. properties配置文件

sqlProperty.properties

#端口号
port=1234
#密码
password=6666

timeProperty.properties

#默认时间2秒
normalTime=2000
#一天
oneDay=86400000

6. 测试(使用)类

复制代码
package action;

import pub.SystemProperty;
import com.opensymphony.xwork2.ActionSupport;

public class TestAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    @Override
    public String execute() throws Exception {

        // 因为是静态变量,所以直接从类名.变量的方式获取
        int port = SystemProperty.port;
        String password = SystemProperty.password;
        
        System.out.println("port=" + port);
        System.out.println("password=" + password);

        //从静态容器中取
        String normalTime = SystemProperty.propList.get("normalTime");
        String oneDay = SystemProperty.propList.get("oneDay");

        System.out.println("normalTime=" + normalTime);
        System.out.println("oneDay=" + oneDay);

        return SUCCESS;
    }
}
复制代码

7. 输出结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值