当前位置:网站首页>Filter与Listener
Filter与Listener
2022-08-05 18:54:00 【night_du】
Filter过滤器
定义
sun公司制定的一种规范,用于处理拦截Servlet的请求并处理通用的逻辑
定义过滤器
- 定义java类,实现Filter接口:使用javax.servlet.*包
- 重写抽象方法:init、doFilter、destory
- 配置过滤器:最好回链,给下一个过滤器使用
流程

优先级
- 当多个filter作用在web组件上,过滤器调用的顺序与web.xml文件中的filter-mapping配置的顺序有关
- 如果是注解,优先级与类名的字符顺序有关
优点
- 灵活,可“插拔性”较好,当需要新增或者减少一个功能时,通过配置快速实现,而且不会影响之前的功能
- 当多个web组件有相同的逻辑需要实现时,可以使用filter处理共同的逻辑,便于后期扩展与维护
注解
@WebFilter("/comment/*") //过滤一种servlet
@WebFilter(urlPatterns = {
"*.admin", "*.userInfo"}) //过滤多种servlet
基本使用
package servlet;
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 java.io.IOException;
@WebServlet("/filter/showServlet")
public class showServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("老污龟");
}
}
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/filter/*")
public class CharacterEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化创建");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//设置编码方式
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
response.setContentType("text/html");
System.out.println("执行前");
chain.doFilter(request, response);
System.out.println("执行后");
}
public void destroy() {
System.out.println("过滤器销毁");
}
}
不使用注解,web.xml配置
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/filter/*</url-pattern>
</filter-mapping>
练习
需求
写一个CommentFilter2,判断评论内容的长度是否超过20,如果超过,输出内容过长,反之,继续调用后续的组件
代码实现
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/comment/*")
public class LengthFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String comment = servletRequest.getParameter("comment");
if (comment.length() > 20) {
servletResponse.getWriter().write("评论内容超长");
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
监听器
定义
sun公司制定的个特殊的类,用来监听容器中产生的一些事件并做相应的处理
两类事件:
- 第一类:与生命周期相关的事件,比如容器中创建或者销毁了request,session,servletContext对象可以进行监听
- 第二类:绑定事件,比如调用了request/session/servletContext三个对象的setAttribute(),removeAttribute()方法
定义监听器
- 定义java类,实现特定的接口
- 重写方法
- 配置监听器
案例
需求
监听当前页面在线人数
代码实现
package listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineCountListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer onlineCount = (Integer) context.getAttribute("onlineCount");
if (onlineCount == null) {
onlineCount = 1;
} else {
onlineCount++;
}
context.setAttribute("onlineCount", onlineCount);
}
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
//se.getSession().invalidate();//销毁
Integer onlineCount = (Integer) context.getAttribute("onlineCount");
if (onlineCount == null) {
onlineCount = 0;
} else {
onlineCount--;
}
context.setAttribute("onlineCount", onlineCount);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>当前有<span><%=this.getServletConfig().getServletContext().getAttribute("onlineCount")%></span> 人在线</h1>
</body>
</html>
边栏推荐
- 面试结束前被问「你有哪些要问我的?」该怎么办?这样回答你就凉了
- “拨”取数字的典例:N位水仙花数判断及水仙花数变种
- 物联网技术融合:ZETA联盟会员推出支持ZETA通信协议的BLE蓝牙网关
- Orchestrator 对 MGR MySQL Group Replication的支持
- 数据库的基础学习1:select语句的查询
- 1. Reporting platform planning
- abaqus不同网格类型生成代码
- div网页布局(做一个简单网页界面为例)
- C陷阱:数组越界遍历,不报错却出现死循环?从内存解析角度看数组与局部变量之“爱恨纠葛”
- 调用colmap作为my项目第三方库,debug进入colmap代码调试--CMakeLists配置
猜你喜欢

一节课掌握大厂技术 委托和反射

阿里巴巴十亿级并发系统设计手册已开源(2022最新版)

2. Pre-research on related components of the reporting platform (1)----jimuReport

张高兴的 .NET IoT 入门指南:(八)基于 GPS 的 NTP 时间同步服务器

ArcGIS Pro scripting tool (11)) of the modified layer value symbol annotations

【Redux】如何实现多组件数据共享

NOKOV度量动作捕捉协助完成无人机室内定位研究

abaqus不同网格类型生成代码

ArcGIS Pro脚本工具(11)——修改图层唯一值符号的标注

国内Api行业,可以内卷到什么程度?
随机推荐
Docker安装Mysql5.7
rhcsa 第二次作业
分析LED透明屏VS常规显示屏优劣
【每日一题】623. 在二叉树中增加一行
数据泄露溯源
从中序与后序遍历序列构造二叉树
在过道里阅读
RHCE 作业七(ansible基础配置详解)
IDEA代码注释模板
abaqus不同网格类型生成代码
#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 002-Go语言环境安装
面试结束前被问「你有哪些要问我的?」该怎么办?这样回答你就凉了
TiUP Cluster
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
模型风险管理简述
RHCE 作业八(Ansible的三个命令模块和部分文件操模块)
OWASP的s-sdlc项目优秀分享
rhcsa 学习笔记(持续更新)
EfficientFormer学习笔记
IDEA运行参数配置