日期:2014-05-16  浏览次数:20394 次

jsp+servlet学习(三)监听器实例

ServletContextListener监听ServletContext一生中两个关键的事件——创建和撤销

下面的实例是通过监听器获取初始化参数,并创建一个Dog对象,存放在ServletContext中。

项目结构如下:

①web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
	<context-param>
		<param-name>dogName</param-name>
		<param-value>TomEgg</param-value>
	</context-param>
	<listener>
		<listener-class>com.zhongqian.listener.TestServletContextListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>testServlet</servlet-name>
		<servlet-class>com.zhongqian.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>testServlet</servlet-name>
		<url-pattern>/testServlet.do</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

②创建TestServletContextListener和TestServlet。

public class TestServletContextListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("get into testServletContextListener contextDestoryed method.");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("get into testServletContextListener's contextInitialized method.");
		ServletContext sc = arg0.getServletContext();
		String dogName = sc.getInitParameter("dogName");
		Dog d = new Dog(dogName);
		sc.setAttribute("dog", d);
	}
}

public class TestServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Dog d = (Dog)this.getServletContext().getAttribute("dog");
		System.out.println(d.getDogName());
	}
}

③创建Dog类

服务器启动时,即调用了监听器。当客户端访问testServlet.do时,在控制台打印TomEgg.


除了上下文监听器外,还有很多其他的监听器。常见的8个监听器如下: