监听器介绍
监听器 - Listener
监听器(Listener)是J2EE Servlet模块下的组件
Listener的作用对web应用对象的行为进行监控
通过Listener监听自动触发指定的功能代码
第一个监听器
package com.imooc.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; @WebListener public class FirstListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("监听器销毁"); } @Override public void contextInitialized(ServletContextEvent arg0) { // TODO Auto-generated method stub System.out.println("监听器初始化"); } }
<listener>
<listener-class>com.imooc.listener.FirstListener</listener-class>
</listener>
内置对象监听器
案例应用
请求流量分析统计
package com.imooc.total; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; public class RequestTotal implements ServletContextListener,ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent arg0) { // TODO Auto-generated method stub } @Override public void requestInitialized(ServletRequestEvent arg0) { /** * 监听请求,每次请求来临时,记录时间段的请求次数 * */ //获取ServletContext对象 ServletContext context = arg0.getServletContext(); //取出属性对象 List<String> timeArray = (List<String>) context.getAttribute("timeArray"); List<Integer> valueArray = (List<Integer>) context.getAttribute("valueArray"); //定义一个时间类型的对象 Date date = new Date(); //时间格式化 SimpleDateFormat hourMinute = new SimpleDateFormat("HH:mm"); //对小时和分钟格式化 String time = hourMinute.format(date); //判断当前时间在不在集合里 if(timeArray.indexOf(time) == -1) { //时间集合里增加这个时间段 timeArray.add(time); //在请求记录集合里,初始化有一次请求 valueArray.add(1); //保存ServletContext对象里 context.setAttribute("timeArray", timeArray); context.setAttribute("valueArray", valueArray); }else { //获取该时间段索引 int index = timeArray.indexOf(time); //根据索引获取值 int value = valueArray.get(index); //根据索引累加值 valueArray.set(index, value+1); //保存属性 context.setAttribute("valueArray", valueArray); } } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { // 初始化时间集合,累加请求集合 List timeArray = new ArrayList(); List valueArray = new ArrayList(); //获取ServletContext对象 ServletContext context = arg0.getServletContext(); //把timeArray当属性保存在ServletContext里 context.setAttribute("timeArray", timeArray); context.setAttribute("valueArray", valueArray); } }
xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>request-total</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>com.imooc.total.RequestTotal</listener-class> </listener> </web-app>
入门百度Echarts组件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/echarts.min.js"></script> <script type="text/javascript" src="js/jquery-3.5.1.min.js"></script> </head> <body> <!-- 为ECharts准备一个具备大小(宽高)的Dom --> <div id="main" style=" 600px;height:400px;"></div> <script type="text/javascript"> function showCase(){ //ajax的使用 $.ajax( { url:"./rt", type:"get", dataType:"json", success : function(json) { // data = jQuery.parseJSON(data); //dataType指明了返回数据为json类型,故不需要再反序列化 console.log(json); console.log(json.timeArray); console.log(json.vauleArray); // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 指定图表的配置项和数据 var option = { title: { text: '请求流量数据表' }, tooltip: {}, legend: { data:['访问量'] }, xAxis: { data: json.timeArray }, yAxis: {}, series: [{ name: '次数', type: 'bar', data: json.valueArray }] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); }, error:function(){ alert("请求失败"); } } ) } window.setInterval("showCase()",1000); </script> </body> </html>
package com.imooc.total; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletRequest; public class RequestTotal implements ServletContextListener,ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent arg0) { // TODO Auto-generated method stub } @Override public void requestInitialized(ServletRequestEvent arg0) { /** * 监听请求,每次请求来临时,记录时间段的请求次数 * */ //获取HttpServletRequest对象 HttpServletRequest request = (HttpServletRequest)arg0.getServletRequest(); //获取请求的URL String url = request.getRequestURL().toString(); if(url.endsWith("/rt") == true) { return; } //获取ServletContext对象 ServletContext context = arg0.getServletContext(); //取出属性对象 List<String> timeArray = (List<String>) context.getAttribute("timeArray"); List<Integer> valueArray = (List<Integer>) context.getAttribute("valueArray"); //定义一个时间类型的对象 Date date = new Date(); //时间格式化 SimpleDateFormat hourMinute = new SimpleDateFormat("HH:mm"); //对小时和分钟格式化 String time = hourMinute.format(date); //判断当前时间在不在集合里 if(timeArray.indexOf(time) == -1) { //时间集合里增加这个时间段 timeArray.add(time); //在请求记录集合里,初始化有一次请求 valueArray.add(1); //保存ServletContext对象里 context.setAttribute("timeArray", timeArray); context.setAttribute("valueArray", valueArray); }else { //获取该时间段索引 int index = timeArray.indexOf(time); //根据索引获取值 int value = valueArray.get(index); //根据索引累加值 valueArray.set(index, value+1); //保存属性 context.setAttribute("valueArray", valueArray); } } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { // 初始化时间集合,累加请求集合 List timeArray = new ArrayList(); List valueArray = new ArrayList(); //获取ServletContext对象 ServletContext context = arg0.getServletContext(); //把timeArray当属性保存在ServletContext里 context.setAttribute("timeArray", timeArray); context.setAttribute("valueArray", valueArray); } }
package com.imooc.total; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; 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 { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // out.println("<h1>流量统计计算器</h1>"); ServletContext context = request.getServletContext(); List<String> timeArray = (List) context.getAttribute("timeArray"); List<Integer> valueArray = (List<Integer>) context.getAttribute("valueArray"); // out.println(timeArray.toString()+" "); // out.println(valueArray.toString()); //整合集合,采取map映射表的方式 Map dict = new HashMap(); //初始化键值对 dict.put("timeArray", timeArray); dict.put("valueArray", valueArray); //转化为JSON字符串 String json = JSON.toJSONString(dict); out.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); } }