实现Tomat等应用服务器启动时自动运行一个类
Published by admin on 03月 15, 2008
在应用中经常有这样的需求,应用服务器启动时就自动运行一段代码以实现某个功能:比如自动提醒功能、或自动统计;以下是实现思路:
1、要求统计tomcat启动的次数,并保存在d:/test.txt中。一个很简单的逻辑。
2、首先编写一个servlet--Startup.java
3、将需要自动运行的操作代码写在init方法中。
4、如下配置web.xml
<servlet>
<servlet-name>startup</servlet-name>
<servlet-class>com.usease.Startup</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
5、 附servlet全代码:
package com.usease;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Startup extends HttpServlet {
private static final String CONTENT_TYPE = “text/html; charset=GBK”;
//Initialize global variables
public void init() throws ServletException {
try {
File file = new File(”d:/test.txt”);
int count = 0;
if (file.exists()) {
BufferedReader in = new BufferedReader(new FileReader(file));
String inString = in.readLine();
count = Integer.parseInt(inString);
in.close();
}
count++;
PrintWriter out = new PrintWriter(new FileOutputStream(”d:/test.txt”));
out.print(count);
out.close();
}
catch (IOException e) {}
System.out.println(”Count completed!”);
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
//Clean up resources
public void destroy() {
}
}
6 、这样,当Tomcat加载这个Context路径的时候,就会自动相应的操作了。

Add A Comment