当前位置:网站首页>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() {
}
}
边栏推荐
- ADC introduction
- Segmentation based deep learning approach for surface defect detection
- nodejs链接mysql报错:ER_NOT_SUPPORTED_AUTH_MODEError: ER_NOT_SUPPORTED_AUTH_MODE
- About student management system (registration, login, student side)
- TM1638 LED数码显示模块ARDUINO驱动代码
- C语言基础
- ARM预备知识
- 一个可以返回前一页并自动刷新页面的ASP代码.
- T5论文总结
- I2C也可总线取电!
猜你喜欢

ESP32连接阿里云MQTT物联网平台

SystemVerilog语法
![[RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)](/img/6e/da80133e05b18c87d7167c023b6c93.gif)
[RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)

nodejs链接mysql报错:ER_NOT_SUPPORTED_AUTH_MODEError: ER_NOT_SUPPORTED_AUTH_MODE

BSP3 电力监控仪(功率监控仪)端子定义和接线

OC -- packaging class and processing object

CCF 201509-3 模板生成系统

无线中继采集仪的常见问题

CCF 201604-2 俄罗斯方块

Mixed supervision for surface defect detection: from weakly to fully supervised learning
随机推荐
MLX90640 红外热成像仪测温模块开发笔记(五)
TM1638 LED数码显示模块ARDUINO驱动代码
TensorFlow raw_rnn - 实现seq2seq模式中将上一时刻的输出作为下一时刻的输入
NLM5系列无线振弦传感采集仪的工作模式及休眠模式下状态
Store to-do items locally (improve on to-do items)
Qt 6.2的下载和安装
CDA Level1知识点总结之多维数据透视分析
Introduction to arm GIC
Arm preliminaries
Introduction to Verdi Foundation
Gartner 2022年顶尖科技趋势之超级自动化
Creation of adjacency table of undirected connected graph output breadth depth traversal
Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (III)
小程序调起微信支付
Mixed supervision for surface defect detection: from weakly to fully supervised learning
Visualization of sensor data based on raspberry pie 4B
看一个双非二本(0实习)大三学生如何拿到阿里、腾讯的offer
概率论与数理统计 4 Continuous Random Variables and Probability Distributions(连续随机变量与概率分布)(上篇)
CCF 201512-4 送货
VScode配置ROS开发环境:修改代码不生效问题原因及解决方法