Listener、Filter、Servlet与Java Web项目初始化的工作

来源:岁月联盟 编辑:exp 时间:2012-04-24

通常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.2cto.com/uploadfile/2012/0424/20120424015209986.zip



摘自 TOM4J