当前位置:网站首页>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
边栏推荐
- How do traditional enterprises cope with digital transformation? These books give you the answer
- 甲辰篇 創世紀《「內元宇宙」聯載》
- 21 days learning mongodb notes
- box-sizing
- leetcode-791. Custom string sorting
- QT double buffer drawing
- Kubernets Getting started tutoriel
- Process virtual address space partition
- C#,二维贝塞尔拟合曲线(Bézier Curve)参数点的计算代码
- BUUCTF WEB [BJDCTF2020]The mystery of ip
猜你喜欢
SSL certificate refund instructions
产品开发都应该知道的8个网站,增强工作体验
box-sizing
I changed to a programmer at the age of 31. Now I'm 34. Let me talk about my experience and some feelings
[csnote] ER diagram
Process virtual address space partition
Homomorphic encryption technology learning
Qt绘制文字
STM32控制步进电机(ULN2003+28byj)
风尚云网学习-h5的input:type属性的image属性
随机推荐
flask项目跨域拦截处理以及dbm数据库学习【包头文创网站开发】
教你快速开发一个 狼人杀微信小程序(附源码)
Analysis of InnoDB execution process in MySQL
风尚云网学习-input属性总结
Deploying MySQL in cloud native kubesphere
SSL certificate refund instructions
QT one process runs another
Recommended website for drawing result map
8 websites that should be known for product development to enhance work experience
产品开发都应该知道的8个网站,增强工作体验
How do traditional enterprises cope with digital transformation? These books give you the answer
21 days learning mongodb notes
使用Source Insight查看编辑源代码
Luogu p5540 [balkanoi2011] timeismoney | minimum product spanning tree problem solution
Use source insight to view and edit source code
Unlock openharmony technology day! The annual event is about to open!
C, calculation code of parameter points of two-dimensional Bezier curve
Kubernets Getting started tutoriel
【每日一题】棋盘问题
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)