Filters and Listeners

filter

what is a filter

·  Filter is a small, pluggable Web component defined in the Servlet2.3 specification . Used to intercept the request and response process of the servlet container in order to view, extract or somehow manipulate the data being exchanged between the client and the server ;

Filters are usually web components that encapsulate some functionality that is important but not deterministic for handling client requests or sending responses;

Typical applications include logging request and response data, managing session attributes, etc .;

How to write a filter

(1) Write a Java class, implement the Filter class, and implement the interception processing logic in the doFilter method
/**
 * @author dream-it
 * 1.Filter is used to handle common business between multiple requests.
 * Such as logging, filtering sensitive words, etc.
 * 2. Use Filter to solve the problem without modifying any Servlet,
 * Only need to create a new filter and configure it, it can greatly
 * Reduce the coupling between business code and Servlet.
 */
public class FirstFilter implements Filter {
	/**
	 * Automatically destroy when tomcat closes
	 */
	public void destroy() {
		System.out.println("销毁FirstFilter");
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("FirstFilter前");
		//Calling doFilter() is to let the request continue to execute. If this method is not called, the request will be interrupted and respond directly.
		//The continued execution of the request will call the subsequent Filter, and finally call the Servlet
		//During this process, Filter and Filter are called in order,
		//And any Filter interrupts the request, which will cause subsequent Filters to fail to execute.
		// Their relationship is like a chain, interlocking. So the object is called FilterChain
		//See the filter call process diagram for details
		chain.doFilter(req, res);
		System.out.println("FirstFilter后");		
	}

	/**
	 * Filter is created and initialized only once when tomcat starts, so it is a singleton.
	 * Objects created by others are basically singletons.
	 */
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("Initialize FirstFilter");
	}
(2) Add the filter to the web application

    Modify the web.xml file and add a node for registering filters

<!-- Declare Filter -->
  <filter>
  	<filter-name>first</filter-name>
  	<filter-class>web.FirstFilter</filter-class>
  </filter>
  <!-- Declare that this Filter can filter/intercept those requests -->
  <filter-mapping>
  	<filter-name>first</filter-name>
  	<!-- The access path of the servlet that can be intercepted, if you write /*, it means everything -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
(3) The filter is packaged and deployed together with the web application

   When deploying a filter with a web application, simply include the filter class with other web component classes; put the web.xml file (along with the filter registration) into the web application structure, and the servlet container will process the other things;

The execution flow of the filter

filter priority

If there are multiple filters that meet the filtering conditions, the container calls each filter according to the order of <filter-mapping >

<filter>...</filter>
<filter>...</filter>

<filter-mapping>...</filter-mapping>
<filter-mapping>...</filter-mapping>

Execution flow of multiple filters

filter initialization parameters

After the container is started, a filter instance will be created;

· Next, the container will call the init method of the filter, and the container will create a FilterConfig object in advance. This object can access some parameters configured in the web.xml file;

These are stored in the web.xml file, read by the FilterConfig object ;

· Through these initialization parameters, some auxiliary parameters can be easily and quickly configured and modified;

Configuration of initialization parameters
<filter>
  	<filter-name>filter</filter-name>
  	<filter-class>web.xxxFilter</filter-class>
  	<!-- Preset a parameter to the current filter -->
  	<init-param>
  		<param-name>city</param-name>
  		<param-value>北京</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>filter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
Read initialization parameters

· Use the FilterConfig object to read and configure initialization parameters in web.xml

String config.getInitParamter("city");

Advantages of filters

Implement the "pluggability" of the code, that is, adding or reducing a function module will not affect the normal execution of the program ;

· Multiple modules with the same processing logic can be written in the filter, which is convenient for code maintenance;

listener

what is a listener

· A special component defined in the Servlet specification, used to monitor events generated by the Servlet container for corresponding processing

Two types of events generated by containers:

  - life cycle related events;

  - Bind data related events;

Lifecycle related events

· Events generated when the container creates or destroys request, session, and ServletContext;

· ServletRequestListener

requestDestroyed(ServletRequestEvent sre);
requestInitialized(ServletRequestEvent sre);

· HttpSessionListener

sessionCreated(HttpSessionEvent se);
sessionDestroyed(HttpSessionEvent se);

· ServletContextListener

contextDestroyed(ServletContextEvent sce);
contextInitialized(ServletContextEvent sce);

Note: Implementing different interfaces will have different implementations;

Binding data related events

· Events generated when the setAttribute and removeAttribute methods of request, session, and ServletContext are called

· ServletRequestAttributeListener

attributeAdded (ServletRequestAttributeEvent srae);
attributeRemoved (ServletRequestAttributeEvent srae);
attributeReplaced (ServletRequestAttributeEvent srae);

· HttpSessionAttributeListener

  - Refer to API documentation

· ServletContextAttributeListener

  - Refer to API documentation

How to write a listener

(1) Write a Java class and choose to implement the corresponding monitoring interface according to the type of monitoring event. For example, to monitor the creation and destruction of Session objects, it is necessary to implement HttpSessionListener;
(2) In the monitoring interface method, implement the corresponding monitoring processing logic;
public class MyListener implements HttpSessionListener,
		HttpSessionAttributeListener {

	public void sessionCreated(HttpSessionEvent e) {
		System.out.println("session创建");
		System.out.println(e.getSession());
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("session销毁");
	}

	public void attributeAdded(HttpSessionBindingEvent arg0) {
		System.out.println("Add data to session");
	}

	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		
	}

	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		
	}

}
(3) Register the listener in the web.xml file;
<listener>
  	<listener-class>web.MyListener</listener-class>
  </listener>

Note: Multiple listeners that implement the same Listener interface are determined according to the order in which the web.xml registration appears during execution;

Application scenarios

· Since the ServletRequest, HttpSession, and ServletContext objects are created by the container, you can know when they are created by registering listeners for these objects. for example:

1) Release application-level resources in the ContextDestroyed method;

2) To count the number of people online, you can monitor the session creation action through the sessionCreated method of the HttpSessionListener listener;

Servlet context

What is a servlet context

After the container is started, a unique object that meets the requirements of the ServletContext interface will be created for each Web application, which is the Servlet context;

· Features

 - Uniqueness (one web application corresponds to one servlet);

 - Always exist (as long as the container is not closed and the application is not uninstalled and deleted, the servlet context will always exist);

How to get Servlet context

· Method 1

 - getServletContext() provided by GenericServlet;

· Method 2

 - getServletContext() provided by ServletConfig;

· Method 3

 - getServletContext() provided by HttpSession;

· Method 4

 - getServletContext() provided by FilterConfig;

The role and characteristics of servlet context

· Function 1

 - use setAttribute to bind data;

· Function 2

 - use removeAttribute to remove bound data;

· Function three

 - Use getAttribute to get binding data;

· Features

 - The data bound by the servlet context can be shared by all components on the entire application and can be accessed all the time;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944274&siteId=291194637