当前位置:网站首页>Filter过滤器详解(监听器以及它们的应用)
Filter过滤器详解(监听器以及它们的应用)
2022-07-25 09:25:00 【Zero摄氏度】
Filter过滤器详解
1.过滤器
Fillter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登录验证…
web服务有一些垃圾请求,后台不应该处理或者应该报错时由过滤器来过滤
2. Filter开发步骤
- 导包
- 编写过滤器
package com.qian.filter;
import javax.servlet.*;
import java.io.IOException;
//初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!
//销毁:eb服务器关闭的时候,才销毁
public class CharacterEncodingFilter implements Filter {
//init: 初始化 destroy:销毁
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
//chain:链
/* 1.过滤中的所有代码,在过滤特定请求的时候都会执行 2.必须要让过滤器继续同行 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=UTF-8");
System.out.println(" CharacterEncodingFilter执行前...");
filterChain.doFilter(servletRequest,servletResponse); // 让我们的请求继续走,如果不写,程序到这里就被拦截停止!
System.out.println(" CharacterEncodingFilter执行后...");
}
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
- 在web.xml中注册过滤器
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.qian.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- 只要是/servlet下的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern> </filter-mapping> 3.监听器
- 实现一个监听器的接口:(有很多种)
- 编写一个监听器,实现监听接口
package com.qian.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听:看你的一举一动
//一旦创建Session就会触发一次这个事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
//一旦销毁Seesion就会触发一次这个事件
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
se.getSession().invalidate();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
/* * Session销毁: * 1.手动销毁:getSession().invalidate(); * * 2.自动销毁---->web.xml中配置 * */
}
}
- web.xml中注册监听器
<!-- 注册监听器-->
<listener>
<listener-class>com.qian.listener.OnlineCountListener</listener-class>
</listener>
<!-- session自动销毁-->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
4.过滤器、监听器的常见应用
监听器:GUI编程中经常使用
登录注销
- 用户登录之后才能进入主页,用户注销后就不能进入主页
//登录
package com.qian.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("Username");
if (username.equals("admin")){
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//注销
package com.qian.servlet;
import com.qian.util.Constant;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
if (user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.qian.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.qian.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.qian.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
jsp设计
<%-- 主页
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 16:52
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>登录成功</h1>
<p><a href="/servlet/logout">注销</a></p>
</body>
</html>
<%-- 登录页面
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 16:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form action=${pageContext.request.contextPath}/servlet/login method="post">
<input type="text" name="username">
<input type="submit">
</form>
<%--页面登录---->提交请求到/servlet/login---->操作请求,成功跳转success--%>
</body>
</html>
<%--错误页面
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/4/11
Time: 20:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录错误</title>
</head>
<body>
<h1>错误</h1>
<h3>没有权限或者用户名错误</h3>
<a href="/login.jsp">返回登录页面</a>
</body>
</html>
- 进入主页的时候要判断用户是否已经登录,要求:在过滤器中实现
package com.qian.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest)servletRequest;
HttpServletResponse response1 = (HttpServletResponse)servletResponse;
Object user_session = request1.getSession().getAttribute("USER_SESSION");
if (request1.getSession().getAttribute("USER_SESSION")==null){
response1.sendRedirect("/Error.jsp");
}
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
}
边栏推荐
猜你喜欢

小程序企业发放红包功能

Development history of convolutional neural network (part)

Hyperautomation for the enhancement of automation in industries 论文翻译
![严重 [main] org.apache.catalina.util.LifecycleBase.handleSubClassException 初始化组件](/img/39/6f6760e80acec0b02028ea2ed1a5b1.png)
严重 [main] org.apache.catalina.util.LifecycleBase.handleSubClassException 初始化组件

【深度学习模型部署】使用TensorFlow Serving + Tornado部署深度学习模型

CCF 201509-3 template generation system

LoRA转4G及网关中继器工作原理

Yolov5 realizes target detection of small data sets -- kolektor defect data set

GCD详解

CCF 201503-4 network delay
随机推荐
预测2021年:加速实现RPA以外的超自动化成果
SystemVerilog syntax
ARM预备知识
LOAM 融合 IMU 细节之 TransformToEnd 函数
[deployment of deep learning model] deploy the deep learning model using tensorflow serving + tornado
Connection and data reading of hand-held vibrating wire vh501tc collector sensor
Solve the problem that esp8266 cannot connect mobile phones and computer hotspots
ARMv8通用定时器简介
一个硬件攻城狮的经济学基础
Creation of adjacency matrix of undirected connected graph output breadth depth traversal
Coredata storage to do list
Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (III)
The economic basis of a hardware siege lion
Swift creates weather app
First knowledge of opencv4.x ---- mean filtering
CCF 201604-2 俄罗斯方块
ISP image signal processing
工程监测无线中继采集仪和无线网络的优势
@5-1 CCF 2019-12-1 reporting
MLX90640 红外热成像传感器测温模块开发笔记(二)