监听器五:监听器使用场景:静态数据预加载;(重要!!!)

前置介绍:

(1)一般一个网页有很多内容,而网页的部分内容可以认为是长时间不变的;比如网页的页眉、页脚或者其他相对不常变化的部分;

(2)对于这些内容,可以看成是网页的静态数据;一般程序开发网页的时候,希望程序员能够把注意力放在网页的请求处理,交互上面;而像加载静态数据这类“看似无关紧要的东西”可可以采用静态数据预加载的方式处理;;;换句话书,这些静态数据的加载,可以不通过后台Servlet处理,而是直接在应用启动的时候,就初始化完成;

(3)而为了实现,应用启动时,完成对静态数据的加载,需要使用监听器;;;这也是监听器一个常见的使用场景。

(4)这篇博客,例子内容不重要,核心是把握例子的思想和整体策略!!!;


实现策略:

这个部分,案例的具体内容不是重点,整体的实现策略,和这个案例的思想最重要!!!

Channel:JavaBean:很简单没什么好说的;

package com.imooc.listener.entity;

public class Channel {
	private String channelName;
	private String url;
	
	public Channel() {}
	public Channel(String channelName, String url) {
		super();
		this.channelName = channelName;
		this.url = url;
	}
	public String getChannelName() {
		return channelName;
	}
	public void setChannelName(String channelName) {
		this.channelName = channelName;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
	

}

……………………………………………………

StaticDataListener:监听器,主要负责应用启动时,在ServletContext全局对象中添加静态数据数据;即这个监听器的作用是初始化数据;

package com.imooc.listener;

import java.util.ArrayList;
import java.util.List;

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

import com.imooc.listener.entity.Channel;

public class StaticDataListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		List list = new ArrayList(); // 在实际中,list不应该写死,而是应该从数据库获取
		list.add(new Channel("免费课程","http://www.imooc.com/1"));
		list.add(new Channel("实战课程","http://www.imooc.com/2"));
		list.add(new Channel("就业班","http://www.imooc.com/3"));
		
		sce.getServletContext().setAttribute("channelList", list);
	}

}

……………………………………………………

index.jsp:这个JSP的主要作用,就是从全局对象中获取数据,并展示

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<c:forEach items="${applicationScope.channelList}" var="c">
		<a href="${c.url}">${c.channelName}</a>|		
	</c:forEach>
	</hr>

</body>
</html>

……………………………………………………

效果:

……………………………………………………

注:在实际开发中,这种静态数据的内容,往往由专人负责;这样可以简化程序员在处理自己负责的业务时候的干扰;也让页面的开发梳理的更清楚;

猜你喜欢

转载自blog.csdn.net/csucsgoat/article/details/114581938