现在的位置: 首页 > 综合 > 正文

在tomcat启动时自动加载一个类

2018年01月28日 ⁄ 综合 ⁄ 共 1498字 ⁄ 字号 评论关闭

有时候在开发web应用的时候,需要tomcat启动后自动加载一个用户的类,执行一些初始化方法,如从数据库中加载业务字典到内存中,因此需要在tomcat启动时就自动加载一个类,或运行一个类的方法。

可以采用在WEB-INF/web.xml中添加一个监听程序(ServletContextListener配置项),步骤如下:
1) 增加一个监听程序 MyServletContextListener.java, 实现javax.servlet.ServletContextListener接口

import java.io.IOException;


import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;


public class OpenOfficeContextListener implements ServletContextListener {


public void contextDestroyed(ServletContextEvent arg0) {

}


public void contextInitialized(ServletContextEvent arg0) {

try {

Process p = Runtime.getRuntime().exec("soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard");

p.waitFor();

System.out.println("OpenOffice注册成功");

} catch (IOException e) {

System.out.println("OpenOffice注册失败");

e.printStackTrace();

} catch (InterruptedException e) {

e.printStackTrace();

}

}


}

2) 配置监听器web.xml:
<listener>
<listener-class>com.util.OpenOfficeContextListener</listener-class>
</listener>
注意:应用事件监听器程序是建立或修改servlet环境或会话对象时通知的类。它们是servlet规范的版本2.3中的新内容。注册一个监听程序涉及在 web.xml的web-app元素内放置一个listener元素。虽然listener元素的结构很简单,但请不要忘记,必须正确地给出web- app元素内的子元素的次序。listener元素位于所有的servlet 元素之前以及所有filter-mapping元素之后。此外,因为应用生存期监听程序是serlvet规范的2.3版本中的新内容,所以必须使用
web.xml DTD的2.3或以后版本,而不是2.2版本,如下:

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
...
</web-app>

抱歉!评论已关闭.