当前位置:网站首页>过滤器 Filter
过滤器 Filter
2022-07-01 03:10:00 【Al_tair】
大家好呀,我是小笙,我和大家分享下我学习Javaweb的笔记
过滤器 Filter
概述
Filter 过滤器它是 JavaWeb 的三大组件之一(Servlet 程序、Listener 监听器、Filter 过 滤器)
Filter 过滤器作用:拦截请求,过滤响应
应用场景:权限检查,日记操作,事务管理
Filter 过滤器是 JavaEE 的规范,是接口
public interface Filter {
void init(FilterConfig var1) throws ServletException;
void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;
void destroy();
}
框架图
示例代码
登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>管理后台登录</title>
</head>
<body>
<h1>管理后台登录</h1>
<form action="<%=request.getContextPath() %>/loginCheckServlet" method="post">
u:<input type="text" name="username"/> <br/>
p:<input type="password" name="password"/> <br/><br/>
<input type="submit" value="用户登录"/>
</form>
</body>
</html>
登录检测
@WebServlet(name = "LoginCheckServlet",urlPatterns = {
"/loginCheckServlet"})
public class LoginCheckServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if("".equals(username) || "".equals(password)){
System.out.println("登录失败");
response.sendRedirect(getServletContext().getContextPath() + "/login.jsp");
return;
}
HttpSession session = request.getSession();
session.setAttribute("name",username);
session.setAttribute("password",password);
response.sendRedirect(getServletContext().getContextPath() + "/manage/admin.jsp");
// request.getRequestDispatcher("/manage/admin.jsp").forward(request,response);
}
}
过滤器
<?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">
<filter>
<filter-name>FilterDemo</filter-name>
<filter-class>com.al_tair.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<url-pattern>/manage/*</url-pattern>
</filter-mapping>
</web-app>
public class FilterDemo implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化成功");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if(request.getSession().getAttribute("name") != null)
filterChain.doFilter(servletRequest,servletResponse);
else
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
@Override
public void destroy() {
System.out.println("过滤器初销毁成功");
}
}
登陆成功
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>管理后台</title>
</head>
<body>
<h1>管理后台</h1>
<h2>登录成功</h2>
</body>
</html>
Filter生命周期
public class FilterDemo implements Filter {
// 当web工程启动时,会执行构造器和init方法
// 创建Filter对象也是单例模式,并且常驻内存直到web工程关闭
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
// 如果匹配到Filter的url-pattern就会调用该方法
// 请求转发可以跳过过滤器
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// FilterChain 接口的 doFilter 方法用于通知 Web 容器把请求交给 Filter 链中的下一个 Filter 去处理,如果当前调用此方法的 Filter 对象是Filter 链中的最后一个 Filter,那么将把请求交给目标 Servlet 程序去处理;如果没有调用该方法默认为拦截,不予通过
filterChain.doFilter(servletRequest,servletResponse);
}
// 当web工程停止时,会执行destroy方法
@Override
public void destroy() {
}
}
FilterConfig
FilterConfig 是 Filter 过滤器的配置类,Tomcat 每次创建 Filter 的时候,也会创建一个 FilterConfig 对象,这里包含了 Filter 配置文件的配置信息
FilterConfig 对象作用是获取 filter 过滤器的配置内容
FilterConfig接口
public interface FilterConfig {
// 获取配置的名称
String getFilterName();
// 获取ServletContext对象,以便于与Servlet进行数据交互
ServletContext getServletContext();
// 获取初始化参数值
String getInitParameter(String var1);
// 获取多个初始化参数值
Enumeration<String> getInitParameterNames();
}
<filter>
<filter-name>FilterConfig_</filter-name>
<filter-class>XXX</filter-class>
<init-param> <!-- 封杀 ip 段 -->
<param-name>ip</param-name>
<param-value>128.12</param-value>
</init-param>
<init-param>
<param-name>port</param-name>
<param-value>8888</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FilterConfig_</filter-name>
<url-pattern>/abc/*</url-pattern>
</filter-mapping>
FilterChain 过滤器链
FilterChain: 在处理某些复杂业务时,一个过滤器不够,可以设计多个过滤器 共同完成过滤任务,形成过滤器链
框架图
代码示例
AFilter
public class AFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("AFilter doFilter");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("AFilter doFilter end");
}
@Override
public void destroy() {
}
}
BFilter
public class BFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("BFilter doFilter");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("BFilter doFilter end");
}
@Override
public void destroy() {
}
}
web.xml
<?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">
<!--FilterChain 过滤器链 -->
<filter>
<filter-name>AFilter</filter-name>
<filter-class>com.al_tair.filter.AFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>BFilter</filter-name>
<filter-class>com.al_tair.filter.BFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>BFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
</web-app>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>FilterChain 过滤器链 完成</h1>
</body>
</html>
显示顺序
注意事项和细节
- 多个 filter 和目标资源在一次 http 请求,在同一个线程中,使用同一个 request 对象
- 多个 filter 执行顺序,和 web.xml 配置顺序保持一致.
边栏推荐
- Summary of problems encountered in debugging positioning and navigation
- Mysql知识点
- Stop saying that you can't solve the "cross domain" problem
- [us match preparation] complete introduction to word editing formula
- 【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
- How do spark tasks of 10W workers run? (Distributed Computing)
- Ctfshow blasting WP
- 伺服第二编码器数值链接到倍福PLC的NC虚拟轴做显示
- Magnetic manometer and measurement of foreign coins
- 限流组件设计实战
猜你喜欢
伺服第二编码器数值链接到倍福PLC的NC虚拟轴做显示
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
Hal library operation STM32 serial port
Druid监控统计数据源
Redis分布式锁的8大坑
EDLines: A real-time line segment detector with a false detection control翻译
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
终极套娃 2.0 | 云原生交付的封装
实战 ELK 优雅管理服务器日志
MySQL index --01--- design principle of index
随机推荐
CX5120控制汇川IS620N伺服报错E15解决方案
IEDA 右键源码文件菜单简介
Elk elegant management server log
Od modify DLL and exe pop-up contents [OllyDbg]
Hal library setting STM32 interrupt
Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
Network address translation (NAT) technology
Clion and C language
Dart training and sphygmomanometer inflation pump power control DPC
Completely solve the lost connection to MySQL server at 'reading initial communication packet
Golang多图生成gif
Stop saying that you can't solve the "cross domain" problem
How to verify whether the contents of two files are the same
倍福TwinCAT3 Ads相关错误详细列表
Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
Huawei operator level router configuration example | BGP VPLS and LDP VPLS interworking example
Edge Drawing: A combined real-time edge and segment detector 翻译
gcc使用、Makefile总结