Listener 4: Comprehensive case: request traffic analysis (important!!!)

This blog is a listener case;

               Which involves the use of listeners;

               The use of Baidu Echarts plug-in;

               Use of JavaScript refresh function;

               There are also some coding ideas and strategies, which can be used for reference !

table of Contents

Zero: description of requirements

One: specific implementation: background data preparation

1. Part 1: Writing the listener

2. The second part: In order to simulate access to this application, add several HTML pages (for access):

3. The third part: In order to display the time and access data on the browser, write a Servlet: RequestTotalServlet:

4. The fourth part, the effect display 

2. Questions, how to make the data displayed in the foreground more beautiful? ? ? ? ? ? Baidu JS plug-in: Echarts plug-in

Three: Specific implementation: front-end data display

0. Basic realization: use Baidu Echarts component to display background data

1. Perfect one: automatic chart refresh

2. Perfection 2: Set it up in the listener to filter certain requests in the business


Zero: description of requirements

Problem elaboration: The following requirement is very suitable to be implemented with a listener;

So this case mainly consists of two parts: the use of listeners to achieve the acquisition of the amount of website visits; the display of chart information;


One: specific implementation: background data preparation

1. Part 1: Writing the listener

RequestTotalListener: listener

        (1) The most important inspiration for the following method of compiling the listener is: for a problem, after sorting out the business, make a logical plan, and then write the program according to the order ;

        (2) The content of this listener is actually very simple, it is ok if you look at it roughly;

        (3) When the global object ServletContext is created, the two parameters timeList and valueList are initialized in the global object; whenever the request object ServletRequest is created, corresponding operations are performed in the timeList and valueList;

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;

/**
 * (1)这个监听器需要实现ServletContextListener和ServletRequestListener接口;a
 * @author Administrator
 *
 */
public class RequestTotalListener implements ServletContextListener,ServletRequestListener{

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

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		// 应用启动的时候,初始化需要存储的数据;
		List timeList = new ArrayList<>();   // 存储时间
		List valueList = new ArrayList<>();  // 具体时间的访问量数据
		// 获取ServletContext对象,并将存储时间和访问量的值存储到这个对象中去;
		// 即每次启动应用,在ServletContext全局对象中初始化这两个可以存储时间和访问量的属性;
		sce.getServletContext().setAttribute("timeList",timeList);
		sce.getServletContext().setAttribute("valueList", valueList);
		
		
	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
		// TimeList:    10:01    10:02    10:05
		// ValueList:    3          6        1         这两个List中的值通过索引精准对应;
		
		List<String> timeList = (List) sre.getServletContext().getAttribute("timeList");
		List<Integer> valueList = (List) sre.getServletContext().getAttribute("valueList");
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		String time = sdf.format(date);
		// indexOf()方法,查找对应的数据在集合中是否存在
		if(timeList.indexOf(time) == -1) {
			timeList.add(time);  // 如果当前时间不存在,就把当前时间添加到timeList中去;
			valueList.add(1);
			sre.getServletContext().setAttribute("timeList", timeList);
			sre.getServletContext().setAttribute("valueList", valueList);
		}else {
			// 获取当前时间在timeList中的索引,在valueList相同索引处的值+1;
			// timeList和valueList,通过索引值的顺序一一对象;
			valueList.set(timeList.indexOf(time), valueList.get(timeList.indexOf(time))+1);
			sre.getServletContext().setAttribute("timeList", timeList);
			sre.getServletContext().setAttribute("valueList", valueList);
		}

	}

}

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

2. The second part: In order to simulate access to this application, add several HTML pages (for access):

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

3. The third part: In order to display the time and access data on the browser, write a Servlet: RequestTotalServlet:

The left and right of this Servlet is to obtain the timeList and valueList in the global object ServletContext; and add them to the response;

package com.imooc.total;

import java.io.IOException;
import java.util.List;

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 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
		List<String> timeList = (List)request.getServletContext().getAttribute("timeList");
		List<Integer> valueList = (List)request.getServletContext().getAttribute("valueList");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(timeList.toString());
		response.getWriter().println("<br/>");
		response.getWriter().println(valueList.toString());
	}

	/**
	 * @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);
	}

}

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

4. The fourth part, the effect display 

At this point, the background data part has been prepared, start the application, and visit several html several times in the browser (in fact, it is also possible to access RequestTotalServlet, and there will be ServletRequest objects created):


2. Questions, how to make the data displayed in the foreground more beautiful? ? ? ? ? ? Baidu JS plug-in: Echarts plug-in

So, the background data is ready, how to better display it in the foreground?

Baidu Echarts chart: You can refer to this blog about Baidu JS component Echarts introduction , and there is a mentality.


Three: Specific implementation: front-end data display

0. Basic realization: use Baidu Echarts component to display background data

The current problem is that the front-end engineer has already completed the front-end interface, and we have also added the front-end development interface to the project. How to upload the back-end data? ? ?

The key to this is communication between the front and back ends!

Common communication methods are Jquery and Ajax: the front-end chart needs to be refreshed locally in real time , so Ajax needs to be used; therefore, as mentioned above, the front-end and back-end communication methods often use Ajax;

(1) The front-end and back-end transmission data mostly adopts JSON format: Therefore, in the Servlet RequestTotalServlet, the data passed to the front desk needs to be converted into JSON format:

(2) The total.html file created by the foreground: the communication between the foreground and the background uses Ajax

<!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>
	<div id="main" style="width: 600px; height: 400px;"></div>
	<script type="text/javascript">
		$.ajax({
			url:"./rt",
			type:"get",
			dataType:"json",
			success:function(json){
				// JavaScript自动将后台传过来的json字符串转成json对象了;
				console.log(json.time);
				console.log(json.value);
				
				//*****************************************************************//
		// 基于准备好的dom,初始化echarts实例
		// 获取div对象,利用echarts.init()对获取的div进行初始化;于是就得到了一个myChart图表对象;
		var myChart = echarts.init(document.getElementById('main'));  

		// 指定图表的配置项和数据
		var option = {
			title : {
				text : '请求流量分析统计'
			},
			tooltip : {},
			legend : {
				data : [ '访问量' ]   // 
			},
			xAxis : {
				data : json.time     // 不得不佩服JavaScript对JSON良好的支持,很给力!!!
			},
			yAxis : {},    // y轴没有设置,表示显示对应的数值;;;数值就在下面的series中定义;
			series : [ {
				name : '访问量',    // 这个需要和上面legend中的data的名称保持对应;
				type : 'line',    // 代表柱状图
				data :json.value
			} ]
		};

		// 使用刚指定的配置项和数据显示图表。
		myChart.setOption(option);   // 激活刚才在option的设置项
				//*****************************************************************//
				
			}
		})
	
	</script>
</body>
</html>

effect:

1. Perfect one: automatic chart refresh

However, there is a problem now: the chart cannot be refreshed automatically, but we need to manually refresh the total.html page to display the latest data in real time: how to do it?

You can query the server for data every second: You need to use JavaScript timers to achieve:

The following changes are made to total.html: (1) The content in the original <script> is transferred to the showChart() method; (2) window.setInterval("showChart()",1000);:Execute showChart( every 1 second ) ) Method; (3) that is, send a /rt request every second to get the latest number of visits;

<!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>
	<div id="main" style="width: 600px; height: 400px;"></div>
	<script type="text/javascript">
		function showChart(){
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
			$.ajax({
				url:"./rt",
				type:"get",
				dataType:"json",
				success:function(json){
				// JavaScript自动将后台传过来的json字符串转成json对象了;
					console.log(json.time);
					console.log(json.value);
				
				//*****************************************************************//
		// 基于准备好的dom,初始化echarts实例
		// 获取div对象,利用echarts.init()对获取的div进行初始化;于是就得到了一个myChart图表对象;
			var myChart = echarts.init(document.getElementById('main'));  

		// 指定图表的配置项和数据
			var option = {
				title : {
					text : '请求流量分析统计'
				},
				tooltip : {},
				legend : {
					data : [ '访问量' ]   // 
				},
				xAxis : {
					data : json.time     // 不得不佩服JavaScript对JSON良好的支持,很给力!!!
				},
				yAxis : {},    // y轴没有设置,表示显示对应的数值;;;数值就在下面的series中定义;
				series : [ {
					name : '访问量',    // 这个需要和上面legend中的data的名称保持对应;
					type : 'line',    // 代表柱状图
					data :json.value
				} ]
			};

		// 使用刚指定的配置项和数据显示图表。
		myChart.setOption(option);   // 激活刚才在option的设置项
				//*****************************************************************//
				
			}
		})
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
		}
		window.setInterval("showChart()",1000);

	
	</script>
</body>
</html>

Effect: It is found that this chart is refreshed every 1 second; however, by browsing the content of total.html, it is found that the request for /rt will also be intercepted by the listener, so the request for /rt will also be intercepted by the listener. Computationally

Therefore, in order to avoid the above request, the request of /rt needs to be excluded, that is, access to /rt should not be included in the increase or decrease of the number of requests:

2. Perfection 2: Set it up in the listener to filter certain requests in the business

You need to set it up in the listener:

 

Effect: It is found that visits/rt is no longer regarded as an increase in the number of visits;

 

Guess you like

Origin blog.csdn.net/csucsgoat/article/details/114377976