当前位置:网站首页>Introduction to servlet listener & filter
Introduction to servlet listener & filter
2022-04-23 12:50:00 【Chase dream Zichen】
1: Monitor Listener
Need to see Servlet Can see my last article , There is a detailed introduction
Listener Introduce :
A listener is to monitor the state change of an object
Event source : The three domain objects being monitored request,session,servletcontext
The writing steps of the listener :
1: Write a listener class to implement the listener interface
Use annotations to configure :@WebListener
Another configuration method is to use web.xml To configure the , But it's more troublesome , I like to use notes
package com.zking.lister;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/** * Monitor * @author JIE * * @date 2022 year 4 month 22 Japan Afternoon 8:21:42 */
@WebListener // Annotation mode
public class onLineListenr implements ServletContextListener,HttpSessionListener {
ServletContext applicaton;
@Override
public void contextDestroyed(ServletContextEvent sce) {
// application Destroyed
System.out.println(" The service was destroyed ");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
//application Was created
System.out.println(" The service created ");
applicaton = sce.getServletContext();
applicaton.setAttribute("onlineCount", 0);
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// The main page of the project was visited
// Number of people obtained
Integer count = (Integer)applicaton.getAttribute("onlineCount");
// The number of +1
// Set number of people
applicaton.setAttribute("onlineCount", ++count);
System.out.println(" Someone came in ");
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// 1. The survival time has expired
//2. Destroy by hand
// Number of people obtained
Integer count = (Integer)applicaton.getAttribute("onlineCount");
// The number of -1
// Set number of people
applicaton.setAttribute("onlineCount", --count);
System.out.println(" Someone's out ");
}
}
2: filter
Filter introduction :
stay Servlet in , We need to Filter To compare and filter information , For example, in a project , We can limit the functions of tourists through filters .
advantage :
The function of the filter is described : While working on the project , Usually divided into several packages , The tourist interface is put in the tourist bag ,
The user interface is placed in the user package , The administrator interface is placed in the administrator package .
So when we write a project, we can use the path matching of the filter to determine , This efficiency will greatly increase
Filter Configuration of :
There are two ways :
1: adopt web.xml To configure the filter
2: Configure filters through annotations ( Personal recommendations )
The first way is more troublesome , The second way is relatively simple , Personally, I like the simpler
package com.zking.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * Permission filter 【 authentication 】 * @author JIE * * @date 2022 year 4 month 22 Japan Afternoon 8:50:11 * */
@WebFilter("/*")
public class Rolefilter implements Filter{
// The path to allow access
List<String> paths=new ArrayList<String>();
{
paths.add("/index.jsp");
paths.add("/tourists.jsp");
paths.add("/login.do");
paths.add("/exit.do");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
// All operations of the filter are completed here
HttpServletRequest request =(HttpServletRequest)req;
HttpServletResponse response =(HttpServletResponse)resp;
// Get the path of the current request
String path=request.getServletPath();
// Path judgment , Use the hypothesis method
boolean f=false;
for (String p : paths) {
if(p.equals(path)) {
f=true;
break;
}
}
if(f) {
// Filter release operation
chain.doFilter(req, resp);
return;
}
Object isLogin= request.getSession().getAttribute("isLogin");
if(isLogin==null) {
response.sendRedirect("index.jsp");
return;
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Java Development Manual ( Development guidelines ):https://pan.baidu.com/s/18cNu2W5p9EumiBZW_yxWIA
Extraction code :a4cb
版权声明
本文为[Chase dream Zichen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231248594291.html
边栏推荐
- ZigBee CC2530 minimum system and register configuration (1)
- 没有空闲服务器?导入 OVF 镜像快速体验 SmartX 超融合社区版
- [wechat applet] Z-index is invalid
- SSL证书退款说明
- Fashion cloud learning - input attribute summary
- A graphic designer's fantasy world | ones characters
- uni-app 原生APP-云打包集成极光推送(JG-JPUSH)详细教程
- Web17——EL与JSTL的使用
- C, calculation code of parameter points of two-dimensional Bezier curve
- 梳理网络IP代理的几大用途
猜你喜欢
Labels and paths
对话PostgreSQL作者Bruce:“转行”是为了更好地前行
NPDP | how can product managers not be excluded by programmers?
【每日一题】棋盘问题
基于卷积神经网络的遥感影像分类识别系统
Message queuing overview
leetcode:437. Path sum III [DFS selected or not selected?]
CVPR 2022&NTIRE 2022|首个用于高光谱图像重建的 Transformer
box-sizing
STM32工程移植:不同型号芯片工程之间的移植:ZE到C8
随机推荐
Kubernets Getting started tutoriel
C#,二维贝塞尔拟合曲线(Bézier Curve)参数点的计算代码
Baserecyclerviewadapterhelper realizes pull-down refresh and pull-up loading
解锁OpenHarmony技术日!年度盛会,即将揭幕!
【vulnhub靶场】-dc2
Dialogue with Bruce, author of PostgreSQL: "changing careers" is to better move forward
【unity笔记】L4Unity中的基础光照
Luogu p5540 [balkanoi2011] timeismoney | minimum product spanning tree problem solution
How do traditional enterprises cope with digital transformation? These books give you the answer
标签与路径
QT one process runs another
QT interprocess communication
MySQL function - recursive function
Unable to create servlet under SRC subfile of idea
Keyword interpretation and some APIs in RT thread
Try the server for one month for free, and attach the tutorial
BUUCTF WEB [BUUCTF 2018]Online Tool
Aviation core technology sharing | overview of safety characteristics of acm32 MCU
【蓝桥杯】4月17日省赛刷题训练(前3道题)
教你快速开发一个 狼人杀微信小程序(附源码)