Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

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>