当前位置:网站首页>Filter and listener
Filter and listener
2022-06-13 04:05:00 【Cavewang】
filter
What is a filter
The filter is actually right web Resource advance ⾏ Intercept , do ⼀ After some processing, I'll give it to ⼀ A filter or servlet Handle , Is usually ⽤ To intercept request Into the ⾏ To deal with the , It can also be used for the returned response Into the ⾏ Intercept processing 
Filter syntax format
- 1. Create a class to implement the interface
public class SignInFilter implements Filter{}
- 2. Override methods in the interface
/* initialization ⽅ Law receive ⼀ individual FilterConfig Parameters of type This parameter is right Filter Of ⼀ Some configuration */
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(" Filter initialization ");
}
/* Filter ⽅ Law It's mainly about request and response Into the ⾏⼀ Some treatment , Then give it to ⼀ A filter or Servlet Handle */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println(" The filter performs processing operations ");
}
/* Destruction method */
public void destroy() {
System.out.println(" The filter has been destroyed ");
}
- 3. stay web.xml Configuration in file
<filter>
<filter-name> Filter name </filter-name>
<filter-class>
The path of the filter
</filter-class>
</filter>
<filter-mapping>
<filter-name> Filter name </filter-name>
<url-pattern> Resources that need to be filtered </url-pattern>
</filter-mapping>
Filter to prevent users from entering the post login page without logging in
Here, we use annotation instead of web.xml Configuration in file
@WebFilter("*")
public class SignInFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(" Filter initialization ");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println(" The filter starts to operate ");
HttpServletRequest request =(HttpServletRequest) servletRequest;
HttpServletResponse response=(HttpServletResponse) servletResponse;
request.setCharacterEncoding("utf-8");
String requestURI =request.getRequestURI();
HttpSession session = request.getSession();
Object username=session.getAttribute("username");
if (requestURI.endsWith("SignUp.jsp")&& username==null){
response.sendRedirect("SignIn.html");
}
filterChain.doFilter(servletRequest,servletResponse);
System.out.println(" End of filter ");
}
@Override
public void destroy() {
System.out.println(" The filter has been destroyed ");
}
}
Monitor
What is a monitor
A listener is a component that listens for changes in the state of a domain object
The concept of the listener :
- Event source : Monitored objects ( Three domain objects request、session、servletContext)
- Monitor : Listen to the event source object. Changes in the state of the event source object will trigger the listener
- Register listener : Connect the listener to the event source ⾏ binding
- Respond to ⾏ by : The function code involved when the listener listens to the state change of the event source ( Programmers write code )
Listener classification
The first dimension
According to the monitored objects :ServletRequest Domain 、HttpSession Domain 、ServletContext Domain
The second dimension
According to the monitoring content : Listen for the creation and destruction of domain objects 、 Listen for changes in the properties of domain objects
| \ | ServletContext Domain | HttpSession Domain | ServletRequest Domain |
|---|---|---|---|
| Creation and destruction of domain objects | ServletContextListener | HttpSessionListener | ServletRequestListener |
| Changes in attributes within domain objects | ServletContextAttributeListener | HttpSessionAttributeListener | ServletRequestAttributeListener |
A listener that monitors the creation and destruction of three domain objects
The writing steps of the listener
1. To write ⼀ A listener class to implement the listener connection ⼝
2. Cover the of the listener ⽅ Law
3. Need to be in web.xml Chin in ⾏ To configure — register
Example
monitor session Creation and destruction of
Here, we use annotation instead of web.xml Configuration in file
@WebListener("*")
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session establish ");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session remove ");
}
}
appendix
ServletContextListener
monitor ServletContext A listener for creating and destroying domains
Servlet Domain ⽣ Life cycle
When to create : Server start creation
When to destroy : The server is shut down and destroyed
ServletContextListener The main work of the listener ⽤
The initialization of the ⼯ do : Initialize object 、 Initialization data ( Load database driver 、 Initialization of connection pool )、 load ⼀ Some initial configurations ⽂ Pieces of (spring Configuration of ⽂ Pieces of )、 Task scheduling ( Timer —Timer/TimerTask)
HttpSessionListener
monitor Httpsession Listener for domain creation and destruction
HttpSession Object's ⽣ Life cycle
When to create : The first ⼀ Secondary modulation ⽤request.getSession Created on
When to destroy : The server is shut down and destroyed 、session Be overdue ( Default 30 minute , Modify the default 30 Minutes is at Tomcat Of web.xml, Modify the current item ⽬ The expiration date of is ⾃⼰ term ⽬ Of web.xml in )、⼿ Move to destroy
HttpSessionListener The main work of the listener ⽤:
Because every visit ⽹ Stations will be created by default session object (jsp⻚⾯ in page Directive session Property defaults to true, I.e. created when accessed session), Sure ⽤ On count ⽹ Station visited ⼈
ServletRequestListener
monitor ServletRequest Listeners for domain creation and destruction
边栏推荐
- Manage PC startup items
- 5G China unicom AP:B SMS ASCII 转码要求
- Data analysis report
- Meaning of different values of margin and padding
- leetcode. 1 --- sum of two numbers
- Value of line height
- 缓存读写--写
- Intervention analysis + pseudo regression
- Use the visual studio code terminal to execute the command, and the prompt "because running scripts is prohibited on this system" will give an error
- Flex layout
猜你喜欢

Introduction to MCU peripherals: temperature sensor DS18B20

Translation of ego planner papers

Among the four common technologies for UAV obstacle avoidance, why does Dajiang prefer binocular vision

环评图件制作-数据处理+图件制作

单片机:A/D(模数转换)的主要指标

Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions

Goframe day 4
![[test development] installation of test management tool Zen path](/img/8b/363e393bdb2d3400a2e8361af8677d.png)
[test development] installation of test management tool Zen path

Single chip microcomputer: a/d differential input signal

Sword finger offer II 022 Entry node of a link in a linked list
随机推荐
Principle, composition and functions of sensors of Dajiang UAV flight control system
Difference between OKR and KPI
Modeling discussion series 143 data processing, analysis and decision system development
Lightweight digital mall system based on PHP
[test development] installation of test management tool Zen path
[test development] automated test selenium (II) -- common APIs for webdriver
ET框架-22 创建ServerInfo实体及事件
谈谈激光雷达的波长
EIA map making - data processing + map making
单片机:RS485 通信与 Modbus 协议
任总与系统工程领域科学家、专家会谈纪要
Call C function in Lua
单片机/嵌入式的实时性疑问解答
dumi 搭建文档型博客
手机私有充电协议解读
Lambda终结操作查找与匹配noneMatch
建模雜談系列143 數據處理、分析與决策系統開發的梳理
不卷了!团队又一位成员离职了。。
Fundamentals of robot obstacle avoidance system
基于PHP的轻量数码商城系统