1.监听器简介
2.第一个监听器
package com.imooc.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
//@WebListener//监听器的注解形式
public class FirstListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
//ServletContext在应用销毁的时候,会触发
System.out.println("ServletContext已销毁");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
//ServletContext在应用重启的时候,会触发
System.out.println("ServletContext已初始化");
}
}
FirstListener
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
com.imooc.listener.FirstListener
3.内置对象监听器
##3.1对象监听
//HelloServlet.java
package com.imooc.listener;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().println("Hello World");
request.getServletContext().setAttribute("sc-attr1", "sc-attr-value1");
request.getSession().setAttribute("session-attr1", "session-attr-value1");
request.setAttribute("request-attr1", "request-attr-value1");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//WebListener.java
package com.imooc.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class WebListener implements ServletContextListener, HttpSessionListener, ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
System.out.println("ServletRequest 已销毁");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
System.out.println("ServletRequest 已被初始化,URI:"+request.getRequestURI());
System.out.println("");
}
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
HttpSession session = se.getSession();
System.out.println("HttpSession已创建,SessionId:"+session.getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
System.out.println("HttpSession 已销毁");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("ServletContext 已初始化");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("ServletContext 已销毁");
}
}
//web.xml
FirstListener
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
com.imooc.listener.FirstListener
com.imooc.listener.WebListener
新开一个浏览器输入http://localhost:8080/FirstListener/hello
,输出如下:
第一部分是新开浏览器,输入地址,session和request创建,然后request立即消失,刷新页面,session不再创建,request重新创建。注意:在关闭浏览器时,session是不会销毁的,session在服务器端,不会因为浏览器关闭就销毁,除非等待30分钟自动销毁或者人为调用代码销毁。
关闭浏览器后重新进入,session又会重建
3.2属性监听
//HelloServlet.java
package com.imooc.listener;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().println("Hello World");
request.getServletContext().setAttribute("sc-attr1", "sc-attr-value1");
request.getSession().setAttribute("session-attr1", "session-attr-value1");
request.setAttribute("request-attr1", "request-attr-value1");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//webAtrributeListener.java
package com.imooc.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* Application Lifecycle Listener implementation class webAtrributeListener
*
*/
@WebListener
public class webAtrributeListener implements ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener {
/**
* Default constructor.
*/
public webAtrributeListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
*/
public void attributeAdded(ServletContextAttributeEvent event) {
// TODO Auto-generated method stub
System.out.println("ServletContext新增属性:"+event.getName()+"->"+event.getValue());
}
/**
* @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
*/
public void attributeRemoved(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
*/
public void attributeReplaced(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
*/
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)
*/
public void attributeAdded(ServletRequestAttributeEvent event) {
System.out.println("ServletRequest新增属性:"+event.getName()+"->"+event.getValue());
}
/**
* @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
*/
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
*/
public void attributeAdded(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
//System.out.println("HttpSession新增属性:"+event.getName()+"->"+event.getValue());
}
/**
* @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
*/
public void attributeRemoved(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
*/
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
}
4.网页访问量实例
4.1 文件列表
4.2 源码
//RequestListener.java
package com.imooc.total;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class RequestListener implements ServletContextListener, ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
String url = request.getRequestURL().toString();
//ajax的请求不算
if(url.endsWith("/rt") == true) {
return;
}
// 每有一个request请求,就执行以下这里的代码,更新时间段的访问次数
List timeList = (List)sre.getServletContext().getAttribute("timeList");
List valueList = (List)sre.getServletContext().getAttribute("valueList");
//TimeList: 10:02 10:03 10:04 10:05
//ValueList: 5 7 10 2
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String time = sdf.format(date);
if(timeList.indexOf(time) == -1) {
timeList.add(time);
valueList.add(1);
sre.getServletContext().setAttribute("timeList", timeList);
sre.getServletContext().setAttribute("valueList",valueList);
}else {
int index = timeList.indexOf(time);
int value = valueList.get(index);
valueList.set(index, value+1);
sre.getServletContext().setAttribute("valueList", valueList);
}
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
List timeList = new ArrayList();
List valueList = new ArrayList();
sce.getServletContext().setAttribute("timeList", timeList);
sce.getServletContext().setAttribute("valueList", valueList);
}
}
//2.RequestTotalServlet.java
package com.imooc.total;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class RequestTotalServlet
*/
@WebServlet("/rt")
public class RequestTotalServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RequestTotalServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//为浏览器输出统计结果
List timeList = (List)request.getServletContext().getAttribute("timeList");
List valueList = (List)request.getServletContext().getAttribute("valueList");
response.setContentType("text/html;charset=utf-8");
// response.getWriter().println(timeList);
// response.getWriter().println("
");
// response.getWriter().println(valueList);
Map result = new HashMap();
result.put("timeList", timeList);
result.put("valueList", valueList);
String json = JSON.toJSONString(result);
response.getWriter().println(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//total.html
Insert title here
//test1.html
//用来产生request请求
Test Page
I'm test page 1
//web.xml
request_total
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
com.imooc.total.RequestListener
5.静态页面内容提前加载
对于一些长期不变的内容,比如
固定内容,其中的数据可以在ServletContext初始化的时候就从数据库中提取出来,写入页面,这种操作可以让固定页面与动态页面分开,使我们重点关注后端的逻辑。也会使两部分的维护比较容易。
Channel.java
package com.imooc.channel;
public class Channel {
private String channelName;
private String url;
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.java
package com.imooc.listener;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.imooc.channel.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.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.xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri= "http://java.sun.com/jsp/jstl/core" %>
Insert title here
${c.channelName}|
//web.xml
ServletProj
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
com.imooc.listener.StaticDataListener