监听器——javaWeb三大组件之一
1.监听器
①ServletContextListener (应用程序监听)
MyApplicationListener:
package com.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* 应用程序监听器,可以监听网站的启动和销毁,并作出对应的处理
*/
//配置监听器,让网站知道有这个对象
@WebListener
public class MyApplicationListener implements ServletContextListener {
/**
* 监听到网站初始化,然后做对应的处理
* @param sce
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("MyApplicationListener监听到了网站的启动。。");
}
/**
* 监听到网站销毁然后做对应的处理
* @param sce
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("MyApplicationListener监听到了网站的销毁。。");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--web.xml配置监听器-->
<!-- <listener>-->
<!-- <listener-class>com.listener.MyApplicationListener</listener-class>-->
<!-- </listener>-->
<!-- <listener>-->
<!-- <listener-class>com.listener.MySessionListener</listener-class>-->
<!-- </listener>-->
<!--用注解方式配置过滤器-->
<!-- <filter>-->
<!-- <filter-name>LoginFilter</filter-name>-->
<!-- <filter-class>com.filter.LoginFilter</filter-class>-->
<!-- <init-param>-->
<!-- <param-name>whiteNames</param-name>-->
<!-- <param-value>/login.jsp,/login,/,/index.jsp</param-value>-->
<!-- </init-param>-->
<!-- </filter>-->
<!-- <filter-mapping>-->
<!-- <filter-name>LoginFilter</filter-name>-->
<!-- <url-pattern>/*</url-pattern>-->
<!-- </filter-mapping>-->
<!-- <filter>-->
<!-- <filter-name>MyFirstFilter</filter-name>-->
<!-- <filter-class>com.filter.MyFirstFilter</filter-class>-->
<!-- </filter>-->
<!--配置过滤器过滤的请求地址-->
<!-- <filter-mapping>-->
<!-- <filter-name>MyFirstFilter</filter-name>-->
<!-- <url-pattern>/*</url-pattern>-->
<!-- </filter-mapping>-->
</web-app>
② HttpSessionListener(会话对象监听)
启动程序时:
避免干扰,将过LoginFilter过滤器注释起来。
LoginFilter:
package com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
//白名单
private String[] whiteNames={"login.jsp","index.jsp","toLogin","login",""};
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//向下转型
HttpServletRequest req=(HttpServletRequest)servletRequest;
HttpServletResponse resp=(HttpServletResponse)servletResponse;
//获取请求路径
String uri=req.getRequestURI();
String process=uri.substring(uri.lastIndexOf("/")+1);
System.out.println("process:"+process);
//定义变量,记录当前请求的资源是否属于白名单
boolean isWhiteName=false;
//判断请求资源是否在白名单内
for(String s:whiteNames){
if(process.equals(s)){
isWhiteName=true;
break;
}
}
//是白名单内的请求,就直接放行
if(isWhiteName){
//通过过滤器链条对象,将请求向后传递
filterChain.doFilter(req,resp);
}else {
//不是白名单的请求,要校验
//如果session没有记录,是非法访问,则跳转到登录
if(req.getSession().getAttribute("userName")==null){
req.setAttribute("error","请先登录。。。");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}else{
//如果session有记录,则放行
filterChain.doFilter(req,resp);
}
}
}
}
代码如下:
MySessionListener:
package com.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* session监听器:监听session的创建和销毁
*/
@WebListener
public class MySessionListener implements HttpSessionListener {
/**
*监听到session创建时做相应的处理
* @param se
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("MySessionListener监听到session创建了:"+se.getSession().getId());
}
/**
*监听到session销毁时,做相应的处理
* @param se
*/
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("MySessionListener监听到session被销毁了:"+se.getSession().getId());
}
}
layout.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/6
Time: 1:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//销毁session
session.invalidate();
%>
</body>
</html>
③HttpSessionAttributeListener(会话属性监听)
将浏览器访问设置成手动的方式:
启动运行程序:
手动访问test.jsp页面:
手动访问test2页面:
当关闭程序的时候,可以看出应用程序监听器还在工作,我们把它注释掉!
代码部分:
MySessionAttributeListener:
package com.listener;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
/**
* 监听在session中添加数据时,会触发执行该方法
* @param se
*/
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("MySessionAttributeListener监听到了添加属性:"+se.getName()+" "+se.getValue());
}
/**
* 监听在session中删除数据时,会触发执行该方法
* @param se
*/
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("MySessionAttributeListener监听到了删除属性:"+se.getName()+" "+se.getValue());
}
/**
* 监听在session中更新数据时,会触发执行该方法
* @param se
*/
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}
test.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/5
Time: 16:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Test页面</h1>
<%
System.out.print("请求到达了Test页面");
session.setAttribute("aaa",100);
%>
</body>
</html>
test2.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/6
Time: 17:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Test2页面</h1>
<%
System.out.print("请求到达了Test2页面");
session.removeAttribute("aaa");
%>
</body>
</html>
④ ServletContextListener, HttpSessionListener
当前设置为手动访问:
用google浏览器访问:
用edge浏览器访问:
设置为自动时的运行结果:
用google浏览器访问:
然后用edge浏览器访问:
代码如下:
AccessCounterListener:
package com.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* 网站访问次数监听器:监听应用程序启动,监听会话创建
*/
@WebListener
public class AccessCounterListener implements ServletContextListener, HttpSessionListener {
//定义应用程序对象
private ServletContext application;
@Override
public void contextInitialized(ServletContextEvent sce) {
//监听网站启动
//获取到容器创建的应用程序对象
application=sce.getServletContext();
//在应用程序对象中存储一个初始化的计数变量
if(application!=null && application.getAttribute("count")==null){
System.out.println("设置了应用程序的初始化:0");
//设置访问次数为0
application.setAttribute("count",0);
}
}
/**
* 监听会话创建
* @param se
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
Integer count= (Integer) application.getAttribute("count");
if(count!=null){
count++;
application.setAttribute("count",count);
}
}
}
index.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/4
Time: 9:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$ <a href="${pageContext.request.contextPath}/LoginServlet/toLogin"></a>
当前网站的访问次数:${count}
</body>
</html>
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118074.html