Servlet filter and listener based on Java (detailed explanation)

1 filter

1. What is the filter?

A special component defined in the servlet specification for intercepting container calls

Note: after the container receives the request, if there is a filter, it will call the filter first, and then call the servlet

2. How to write a filter?

1. Write a Java class to implement the filter interface;

2. Implement the interception method in the interface method;

3. Configure the filter (web. XML);

3. Configure initialization parameters

1. Configure initialization parameters (init-param)

2. Read the initialized value through the getinitparamenter method provided by filterconfig

4. Priority:

When multiple filters meet the interception requirements, the container executes according to the sequence of < filter mapping > configuration

2 listener

1. What is a listener?

A special attribute defined in the servlet specification is used to listen for events generated by the container

Note: there are two categories of events

1) Events related to the declaration cycle:

It refers to the event generated when the container creates or destroys request, session and servlet context objects

2) Events related to binding data:

It refers to the event generated when request, setAttribute and removeattrbute of servlet context are called

1. How to write a listener?

1. Write a Java class to implement the listener interface

Note: select the corresponding interface according to the event type to listen to. For example, to listen to the event created or destroyed by a session, you need to implement the httpsessionlister interface

2. In the interface method, implement the listening and processing logic;

3. Configure the listener (web. XML)

2. Servlet context

1. What is a servlet context?

After the container is started, a unique object conforming to the ServletContext interface will be created for each web application, which is the servlet context

2. Features:

1) Uniqueness: a web application corresponds to a servlet context

2) Persistence: as long as the server is not shut down and the application is not uninstalled, the context will remain

1. How to get servlet context?

Genericservlet, ServletConfig, filterconfig and httpsession all provide a method (getservletcontext)

2. Role of context

1) Binding data

setattribute,getattribute,removeattribute

Note: compare from the length of survival time: request < session < context

When the use conditions are met, those with short declaration period are preferred

2) Read global initialization parameters

The above article based on java servlet filter and listener (detailed explanation) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>