Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

3.5. Listener

3.5.1. web.xml

配置监听器

		
	<listener>
		<listener-class>cn.netkiller.listener.NewsListener</listener-class>
	</listener>
		
		

3.5.2. NewsListener 类

实现 ServletContextListener 接口

		
package cn.netkiller.listener;   
    
import java.util.Timer;

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

import org.apache.log4j.Logger;

public class NewsListener implements ServletContextListener {   
  
	private static final Logger log = Logger.getLogger(NewsListener.class);
	
	private Timer timer = null;
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		
		log.info("Listener start");
      
		timer = new Timer(true);		
		timer.schedule(new NewsTask(event.getServletContext()), 3*1000, 5*60*1000);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		if (timer != null) {
			timer.cancel();
		}
		log.info("Listener end");
	}   
} 
		
		

3.5.3. NewsTask 类

继承 TimerTask

		
package cn.netkiller.listener;

import java.util.List;
import java.util.TimerTask;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.netkiller.service.interface.NewsService;

public class NewsTask extends TimerTask{
	
	private ServletContext context;
	private static final Logger log = Logger.getLogger(NewsTask.class);
	
	public NewsTask(ServletContext context) {
		this.context = context;
	}
	
	@Override
	public void run() {
		NewsService newsService = (NewsService) WebApplicationContextUtils.getWebApplicationContext(context).getBean("newsService");
		
		try {
			List<cn.netkiller.listener.News> newsList = newsService.getNews();
			context.setAttribute("newsList", newsList);
			
			log.info("Getting News Finished");
		} catch (Exception e) { e.printStackTrace(); }
	}
}
		
		

3.5.4. JSP 中心显示

使用c:forEach显示列表

		
	<div class="news">
       	<c:forEach items="${newsList}" var="news" varStatus="index">
       		<a href="/news/${news.Id}">${news.title}</a>
       	</c:forEach>
	</div>
		
		
comments powered by Disqus