文章目录
一、课程目标
【理解】过滤器的概念
【掌握】过滤器的使用
【了解】监听器的概念
【理解】监听器的使用
二、过滤器
2.1 概念
当客户端发送请求至服务器端,服务器端可以配置过滤器对请求在执行前进行过滤操作,本质就是一个实现了过滤器接口的java类,通过doFilter方法进行请求的过滤与放行
2.2 工作流程
当客户端发送请求时,先由tomcat服务器处理请求,解析请求的地址路径,与web.xml中过滤器过滤地址进行匹配,如果匹配则执行对应过滤器doFilter方法,进行过滤操作,执行结束后通参数继续调用其他符合配置的过滤器。直至没有匹配调用对应的servlet进行处理,返回数据
2.3 生命周期
在服务器启动时自动读取web.xml创建单例过滤器对象,在执行过程中指定路径进行过滤,在服务器正常关闭时自动调用销毁方法进行销毁
2.4 书写语法
1、创建class类实现import javax.servlet.Filter接口
2、重写init doFilter destroy方法
doFilter :书写时注意 在书写通用过滤方法后一定调用chain.doFilter(request, response);进行继续执行,否则会将请求终止
3、在web.xml书写配置文件
<filter>
<filter-name>自定义过滤器名</filter-name>
<filter-class>创建的过滤器class路径</filter-class>
</filter>
<filter-mapping>
<filter-name>自定义过滤器名</filter-name>
<url-pattern>过滤的路径可以过滤全部/* 也可以过滤指定后缀 *.do</url-pattern>
</filter-mapping>
2.5 实例
2.5.1 编码过滤器
创建编码过滤器在配置中设置编码,统一过滤所有请求设置请求相应编码
EnCodingFilter.java
package com.yunhe.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EnCodeingFilter implements Filter {
private String code;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
code = filterConfig.getInitParameter("encode");
Filter.super.init(filterConfig);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("编码过滤器执行");
request.setCharacterEncoding(code);
response.setCharacterEncoding(code);
response.setContentType("text/html;charset="+code);
chain.doFilter(request, response);
}
}
web.xml
<filter>
<filter-name>EnCodeingFilter</filter-name>
<filter-class>com.yunhe.filter.EnCodeingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EnCodeingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
2.5.2 权限过滤器
像是shiro或者spring sercurity 这样的权限框架底层都是使用过滤器进行权限操作
IsLoginFilter.java
package com.yunhe.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class IsLoginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//是否登录权限过滤器
//通过地址过滤 进入该过滤器的请求必须确保登录才能放行
//注意该过滤器忽略登录请求的过滤否则永远不能登录
HttpServletRequest req=(HttpServletRequest) request;
// String servletPath = req.getServletPath();
// System.out.println(servletPath);
HttpServletResponse res=(HttpServletResponse) response;
HttpSession session = req.getSession();
if(session.getAttribute("username")==null){
res.sendRedirect("login");
}else{
chain.doFilter(request, response);
}
}
}
web.xml
<filter>
<display-name>IsLoginFilter</display-name>
<filter-name>IsLoginFilter</filter-name>
<filter-class>com.yunhe.filter.IsLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>IsLoginFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
三、监听器
3.1 概念
创建监听器根据监听的事件实现对应的监听接口,当服务器运行发送对应事件时会自动调用对应方法进行处理
3.2 书写语法
1、创建监听器类根据需求实现相应监听接口
2、实现相应事件对应的回调方法
3、在web.xml中书写配置文件在服务器启动时创建监听器对象
监听全部监听器如下
MyListener.java
package com.yunhe.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyListener implements ServletContextListener, ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener, HttpSessionBindingListener, ServletRequestListener, ServletRequestAttributeListener {
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
public void attributeRemoved(ServletContextAttributeEvent scae) {
// TODO Auto-generated method stub
}
public void attributeAdded(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
public void attributeReplaced(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
}
public void sessionWillPassivate(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
public void attributeAdded(ServletContextAttributeEvent scae) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
*/
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
*/
public void attributeRemoved(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
*/
public void valueBound(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestListener#requestInitialized(ServletRequestEvent)
*/
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionActivationListener#sessionDidActivate(HttpSessionEvent)
*/
public void sessionDidActivate(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
/**
* @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
*/
public void attributeReplaced(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
*/
public void attributeAdded(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
*/
public void attributeRemoved(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
*/
public void attributeReplaced(ServletContextAttributeEvent scae) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
*/
public void valueUnbound(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
}
web.xml
<listener>
<listener-class>com.yunhe.listener.MyListener</listener-class>
</listener>
3.2.1 ServletContext监听器
对application作用域进行监听
package com.yunhe.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class AppListener implements ServletContextListener, ServletContextAttributeListener {
public void attributeAdded(ServletContextAttributeEvent scae) {
System.out.println("当向application作用域赋值时执行");
}
public void attributeRemoved(ServletContextAttributeEvent scae) {
System.out.println("当删除application作用域值时执行");
}
public void attributeReplaced(ServletContextAttributeEvent scae) {
System.out.println("当修改application作用域值时执行");
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("当上下文对象销毁时执行");
}
public void contextInitialized(ServletContextEvent sce) {
System.out.println("当上下文对象创建时执行");
}
}
3.2.2 Request监听器
用于监听客户端的请求相应事件
package com.yunhe.listener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class Reqlistener implements ServletRequestListener, ServletRequestAttributeListener {
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("当服务器接受请求时执行");
}
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("当服务器接受响应接受请求时执行");
}
public void attributeAdded(ServletRequestAttributeEvent srae) {
System.out.println("当向request作用域赋值时执行"+srae.getValue());
}
public void attributeReplaced(ServletRequestAttributeEvent srae) {
String name = srae.getName();
HttpServletRequest request = (HttpServletRequest) srae.getServletRequest();
Object attribute = request.getAttribute(name);
System.out.println("当修改request作用域值时执行"+name+""+srae.getValue()+"=>"+attribute);
}
public void attributeRemoved(ServletRequestAttributeEvent srae) {
System.out.println("当删除request作用域值时执行"+srae.getValue());
}
}
3.2.3 Session监听器
用于监听会话相关的事件.与其他监听器实现一样只需要实现生命周期监听与数据设置修改即可
package com.yunhe.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener{
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session创建时执行");
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session销毁时执行");
}
/**
* @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
*/
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("向session作用域赋值时执行");
}
/**
* @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
*/
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("删除session作用域值时执行");
}
/**
* @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
*/
public void attributeReplaced(HttpSessionBindingEvent se) {
System.out.println("修改session作用域值时执行");
}
}
3.3 实例
使用ajax+监听器实现统计实施展示当前登录人数
a.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="static/js/jquery-3.4.1.min.js" ></script>
<script>
$(function(){
window.setInterval(function(){
$.get("count",function(res){
$("#count").html(res)
})
},1000)
})
</script>
</head>
<body>
当前在线人数: <span id="count"></span>
<a href="out">退出</a>
</body>
</html>
CountServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//保证每个用户都会创建session
HttpSession session = request.getSession();
Object attribute = this.getServletContext().getAttribute("Peoplecount");
response.getWriter().print(attribute);
}
}
OutServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
}
}
PeoplecountListener.java
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class PeoplecountListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
ServletContext application = se.getSession().getServletContext();
Object attribute = application.getAttribute("Peoplecount");
if(attribute==null){
application.setAttribute("Peoplecount", 1);
}else{
application.setAttribute("Peoplecount", (Integer)attribute+1);
}
}
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext application = se.getSession().getServletContext();
Object attribute = application.getAttribute("Peoplecount");
application.setAttribute("Peoplecount", (Integer)attribute-1);
}
}
web.xml
<servlet>
<description></description>
<display-name>CountServlet</display-name>
<servlet-name>CountServlet</servlet-name>
<servlet-class>com.yunhe.servlet.CountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/count</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.yunhe.filter.PeoplecountListener</listener-class>
</listener>
<servlet>
<description></description>
<display-name>OutServlet</display-name>
<servlet-name>OutServlet</servlet-name>
<servlet-class>com.yunhe.servlet.OutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OutServlet</servlet-name>
<url-pattern>/out</url-pattern>
</servlet-mapping>