1.監(jiān)聽器簡介
2.第一個(gè)監(jiān)聽器
package com.imooc.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
//@WebListener//監(jiān)聽器的注解形式
public class FirstListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
//ServletContext在應(yīng)用銷毀的時(shí)候,會觸發(fā)
System.out.println("ServletContext已銷毀");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
//ServletContext在應(yīng)用重啟的時(shí)候,會觸發(fā)
System.out.println("ServletContext已初始化");
}
}
<?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>FirstListener</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.listener.FirstListener</listener-class>
</listener>
</web-app>
3.內(nèi)置對象監(jiān)聽器
##3.1對象監(jiān)聽
//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已創(chuàng)建午衰,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
<?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>FirstListener</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.listener.FirstListener</listener-class>
</listener>
<listener>
<listener-class>com.imooc.listener.WebListener</listener-class>
</listener>
</web-app>
新開一個(gè)瀏覽器輸入http://localhost:8080/FirstListener/hello
,輸出如下:
第一部分是新開瀏覽器,輸入地址,session和request創(chuàng)建引谜,然后request立即消失,刷新頁面擎浴,session不再創(chuàng)建员咽,request重新創(chuàng)建。注意:在關(guān)閉瀏覽器時(shí)贮预,session是不會銷毀的贝室,session在服務(wù)器端契讲,不會因?yàn)闉g覽器關(guān)閉就銷毀,除非等待30分鐘自動銷毀或者人為調(diào)用代碼銷毀滑频。
關(guān)閉瀏覽器后重新進(jìn)入捡偏,session又會重建
3.2屬性監(jiān)聽
//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.網(wǎng)頁訪問量實(shí)例
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;
}
// 每有一個(gè)request請求,就執(zhí)行以下這里的代碼,更新時(shí)間段的訪問次數(shù)
List<String> timeList = (List)sre.getServletContext().getAttribute("timeList");
List<Integer> 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 {
//為瀏覽器輸出統(tǒng)計(jì)結(jié)果
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);
// response.getWriter().println("<br/>");
// 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
<!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.3.1.min.js"></script>
</head>
<body>
<!-- 為 ECharts 準(zhǔn)備一個(gè)具備大邢棵浴(寬高)的 DOM -->
<div id="main" style="width: 600px; height: 400px;"></div>
<script type="text/javascript">
function showChart(){
$.ajax({
"url":"./rt",//這里也是一個(gè)request請求银伟,所以會出現(xiàn)自增現(xiàn)象
"type":"get",
"dataType":"json",
"success":function(json){
console.log(json.timeList);
console.log(json.valueList);
// 基于準(zhǔn)備好的dom,初始化echarts實(shí)例
var myChart = echarts.init(document.getElementById('main'));
// 指定圖表的配置項(xiàng)和數(shù)據(jù)
var option = {
title : {
text : '請求瀏覽分析'
},
tooltip : {},
legend : {
data : [ '訪問量' ]
},
xAxis : {
data : json.timeList//后臺拿數(shù)據(jù)
},
yAxis : {},
series : [ {
name : '訪問量',
type : 'line',
data : json.valueList //后臺拿數(shù)據(jù)
} ]
};
// 使用剛指定的配置項(xiàng)和數(shù)據(jù)顯示圖表绘搞。
myChart.setOption(option);
}
})
}
window.setInterval("showChart()",1000);
</script>
</body>
</html>
//test1.html
//用來產(chǎn)生request請求
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body>
<h1>I'm test page 1</h1>
</body>
</html>
//web.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.RequestListener</listener-class>
</listener>
</web-app>
5.靜態(tài)頁面內(nèi)容提前加載
對于一些長期不變的內(nèi)容彤避,比如
固定內(nèi)容,其中的數(shù)據(jù)可以在ServletContext初始化的時(shí)候就從數(shù)據(jù)庫中提取出來夯辖,寫入頁面琉预,這種操作可以讓固定頁面與動態(tài)頁面分開,使我們重點(diǎn)關(guān)注后端的邏輯蒿褂。也會使兩部分的維護(hù)比較容易圆米。
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
//在實(shí)際開發(fā)中,這里應(yīng)該是從數(shù)據(jù)庫中提取所需要的靜態(tài)數(shù)據(jù)
List list = new ArrayList();
list.add(new Channel("免費(fèi)課程","http://www.imooc.com/1"));
list.add(new Channel("實(shí)戰(zhàn)課程","http://www.imooc.com/2"));
list.add(new Channel("就業(yè)班","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" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<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>
//web.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>ServletProj</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.listener.StaticDataListener</listener-class>
</listener>
</web-app>