通常JavaWeb項目啟動時我們需要做一些初始化工作,比如配置緩存、定時任務等等。舉個例子:我在國內某公司曾經負責維護公司內部的全球通信系統的服務端,公司員工在10W人以上,需要初始化的內容就是將這10W多的用戶信息,在系統啟動時就初始化到緩存中,用戶通過客戶端登陸,像服務端發出請求後,直接從緩存裡面驗證用戶的信息,這樣做的好處是減輕服務端和數據庫的壓力;還有一個好處就是,當員工從客戶端登陸時,系統需要經過一系列的鑒權,過程非常復雜,而處理鑒權的過程很耗費時間,這樣就非常影響員工使用客戶端的體驗,在服務器端配置緩存,能很好的解決這些麻煩。
下面代碼是模擬初始化的一個示例,可以在控制台看到程序的輸出,和Listener、Filter、Servlet的啟動先後順序,強烈建議跟我一樣喜歡動手的Coder操作一下,廢話不多說,直接上代碼了。
[java] package com.tom.servlet;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class HelloListener implements ServletContextListener {
public HelloListener() {
System.out.println("Listener() ----------");
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Listener contextDestroyed()-----------------");
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Listener contextInitialized()-----------------");
Timer timer = new Timer();
timer.schedule(new TimerTest02(), 0, 4000L);
}
}
[java]
package com.tom.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class HelloFilter implements Filter {
private Long seconds;
public HelloFilter() {
System.out.println("+++++ Filter() +++++");
}
public void init(FilterConfig config) throws ServletException {
System.out.println("+++++ FilterInit() +++++");
this.seconds = Long.parseLong(config.getInitParameter("seconds"));
TimerTest.initTimer(seconds);
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("+++++ doFilter() +++++");
}
public void destroy() {
this.seconds = null;
}
public Long getSeconds() {
return seconds;
}
}
[java]
package com.tom.servlet;
import java.io.IOException;
import java.util.Timer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = -7693562670980406523L;
public HelloServlet() {
System.out.println("----- Servlet() -----");
}
public void init() throws ServletException {
System.out.println("----- ServletInit() -----");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTest01(), 0, 6000L);
}
public void destroy() {
System.out.println("----- ServletDestroy() -----");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
[java]
package com.tom.servlet;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TimerTest {
private static int i = 0;
public static void initTimer(Long seconds) {
TimerTest.schedule(new TimerTask() {
public void run() {
callUsers();
}
}, 0, seconds*1000);
}
public static void callUsers() {
System.out.println("Filter refreshed: " + ++i + " times.");
}
public static void schedule(TimerTask task, long delay, long period) {
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(task, delay, period,
TimeUnit.MILLISECONDS);
}
}
class TimerTest01 extends TimerTask {
private static int i = 0;
@Override
public void run() {
System.out.println("Servlet refreshed: " + ++i + " times.");
}
}
class TimerTest02 extends TimerTask {
private static int i = 0;
@Override
public void run() {
System.out.println("Listener refreshed: " + ++i + " times.");
}
}
[html]
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>HelloFilter</filter-name>
<filter-class>com.tom.servlet.HelloFilter</filter-class>
<init-param>
<param-name>seconds</param-name>
<param-value>5</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HelloFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.tom.servlet.HelloServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.tom.servlet.HelloListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
以上代碼是純web項目下的示例,不依賴當下流行的任何開發框架;當然項目初始化還有一些其他的解決方案,比如在Struts1.X下的ActionServlet、Struts2.X下的FilterDispatcher,都可以解決,本例不再贅述,喜歡的可以去研究一下。
本例中代碼供大家參考,歡迎交流並提出批評指正!
為了方便大家在IDE中閱讀,特意將示例項目打包,下載地址:http://www.BkJia.com/uploadfile/2012/0424/20120424015209986.zip
摘自 TOM4J