Introduction and simple use of listener and filter listeners and filters

Overview of listeners

1. What is a listener

A listener is a Java class that implements a specific interface. This Java class is used to listen for changes in methods or properties of another Java class. When the listener object sends an appeal event, a method of the listener will be executed immediately.

2. Purpose of the listener

It is used to monitor the changes of other objects. It is mainly used for graphical interface development

GUI in Java, android.

3. Terms of listener

Event source: refers to the monitored object

Listener: refers to the listening object

Binding: event source binding listener

Event: refers to the change of the event source object - get the event source object

4. Listener execution process

 

Listener in Servlet

Several types of listeners are defined in the servlet. The event sources they use to listen to are servletContext, HttpSession and ServletRequest.

1. Classification of listeners in Servlet

Category III:

The first type: listeners that listen to the creation and destruction of three domain objects (three)

The second category: listeners (three) that listen for attribute changes (attribute addition, removal and replacement) of three domain objects

The third category: listening for javaBean state changes (passivation, activation, binding and unbinding) in HttpSession (two)

first kind  

  Use of ServletContextListener listeners

    Listener used to listen for the creation and destruction of servletcontext domain objects

     Creation and destruction of ServletContext

        Create: create a separate servletcontext object for each web application when the server starts

        Destroy: when the server is shut down, or when the project is removed from the web server

     Method of ServletContextListener listener listener

      Listen for ServletContext creation:

      Listen for destruction of ServletContext:

    Configurator listener

  <listener>
    <listener-class>com.mzxy.listener.weblistener.MyServletContextListener</listener-class>
  </listener>
  

 

    ServletContextListener enterprise usage

        1. Load the configuration file of the framework:

              The Spring framework provides a core listener, contextloadlistener

        2. Scheduled task scheduling.

  

Use of HttpSessionListener listener

    Role of HttpSessionListener listener

          Used to listen for the creation and destruction of HttpSession objects

    Creation and destruction of HttpSession

          Create: the first time the server calls the getSession () method;

          Destruction:

                    Abnormally shut down the server (normally shut down the server session will be serialized)

                    Session expires (30 minutes by default)

                    Manually call the session.invalidate () method

    Method of HttpSessionListener listener

          Listen for HttpSession creation:

          Listen for HttpSession destruction:

    Some small problems about the listener

  1. If you access an HTML, will a session be created    : can't
  2. If you access a jsp, will a session be created    : Yes (the getSession method is called by default when converting to a servlet program)
  3. If you access a servlet, will a session be created    : No (getSession method is not called by default)

Use of ServletRequestListener listener

    Role of ServletRequestListener listener

        Used to listen for the creation and use of ServletRequest objects

    Creation and destruction of ServletRequest object

        Create: once a request is sent from the client to the server, the server will create a request object

        Destroy: after the server responds to this request, the request object is destroyed.

    Methods in ServletRequestListener

        Listen for the creation of ServletRequest:

        Listen for destruction of ServletRequest:

      doubt

  1. Does accessing an HTML page create a request object     : meeting
  2. Does accessing a jsp page create a request object           : meeting
  3. Does the access servlet program create a request object    : meeting

Type II

A listener that listens for property changes of three domain objects

   ServletContextAttributeListener

  1. Listener that listens to attribute variables (attribute addition, removal, replacement) in the ServletContext object
  2. method:

   HttpSessionAttributeListener

  1. Listener that listens to attribute variables (attribute addition, removal, replacement) in HttpSeesion object
  2. method

   ServletRequestAttributeListener

  1. Listener that listens to attribute variables (attribute addition, removal, replacement) in the ServletRequest object
  2. method

  (the methods in the three listeners are the same, but the parameters passed in are different)

    The three usage methods are also consistent. Write classes and then configure classes.

 

Category III

Listener that listens for state changes of Java classes in HttpSession

    Overview of the third type of listener

      Java classes saved in the session domain can have a variety of states: bind to the session, unbind from the session, bring them to a storage device with the persistence of the session object (conversion), and recover from a storage device with the session object (activation).

      Two special listener interfaces are defined in the Servlet object to help Java classes understand their state in the session domain.

          HttpSessionBindingListener interface

          HttpSessionActivationListener interface

      The to implement these two classes does not need to be configured in web.xml

   HttpSessionBindingListener

        Listen for the binding and unbinding status of Java classes in httpsession

        method:

 

Code demonstration: bean1.Java, demo3.jsp.

bean1.java
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
 * Listener that listens to the binding and unbinding of Java classes in HttpSession
 * @author Warm
 *
 */
public class Bean1 implements HttpSessionBindingListener{

	private String name;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name=name;
	}
	@Override
	public void valueBound(HttpSessionBindingEvent arg0) {
		System.out.println("Bean1 And session Bound");
	}

	@Override
	public void valueUnbound(HttpSessionBindingEvent arg0) {
		System.out.println("Bean1 And session Unbound");
	}

}

demo3.jsp:
<%@page import="com.itheima.listener.bean.Bean1"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
 Bean1 bean1 = new Bean1();
 bean1.setName("Zhang San");
 //Binding must be a Java object. Put it inside
 session.setAttribute("bean1", bean1);
 
 session.removeAttribute("bean1");
%>
</body>
</html>

   HttpSessionActivationListener

 

Code: bean2.java+demo4.jsp+demo5.jsp

bean2.java
import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
/**
 * Passive activation listener listening to objects in HttpSession
 * @author Warm
 *
 */
public class Bean2 implements HttpSessionActivationListener,Serializable{

	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public void sessionDidActivate(HttpSessionEvent arg0) {
		System.out.println("Bean2 Sink quilt session Activated");
	}

	@Override
	public void sessionWillPassivate(HttpSessionEvent arg0) {
		System.out.println("Bean2 Sink quilt session Passivated");
	}

}


demo4.jsp:
<%@page import="com.itheima.listener.bean.Bean2"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
 Bean2 bean2 = new Bean2();
 bean2.setName("Zhang San");
 session.setAttribute("bean2", bean2);
%>
</body>
</html>

demo5.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${bean2.name}
</body>
</html>

    Complete the serialization and deserialization of session s through configuration

The Context tag can be configured in:

        Tomcat/conf/context.xml   :  All false hosts under tomcat and projects under virtual directories will serialize session s.

      Tomcat/conf/Catalina/localhost/context.xml :   All items under localhost virtual host will be serialized to session

        Project / META-INF/context.xml   : The current project will be serialized session

 

<Context>

<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">

     <Store className="org.apache.catalina.session.FileStore" directory="itheima"/>

</Manager>

</Context>

directory="itheima": this folder will be created by the system

maxIdleSwap="1": if you do not operate for one minute, it will be serialized automatically

Filter overview

1. What is a Filter

Filter is called filter. It is the most practical technology in Servlet Technology. Web developers intercept the resources managed by web services (jsp, servlet, static picture or static html file) through filter technology, so as to realize some special functions.

Filter is to filter the requests sent from the client to the server

2. Why learn filters

3. Introduction to filter

We show through code:

FilterDemo1 .java
public class FilterDemo1 implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("FilterDemo1 Was created");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("FilterDemo1 Yes");
		//Release
		chain.doFilter(request, response);	
		System.out.println("FilterDemo1 The execution is over");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("FilterDemo1 Destroyed");
		
	}

}


fdemo1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>dmeo1 page</h1>
<%
   System.out.println("demo1 Yes");
%>
</body>
</html>

4. Overview of filterchain object

  What is FilterChain

     FilterChain Filter chain: in a web application, multiple filters can be developed and written. These filters are called a Filter chain.

     The Web server determines which filter to call first according to the registration order of the filter in the web.xml file (the configuration order of mapping). Call the following filters in turn, if there is no next filter. Call the target resource.

Let's demonstrate: the demonstration of FilterChain

First, let's configure the web.xml

<!-- filter -->
  <filter>
    <filter-name>FilterDemo1</filter-name>
    <filter-class>com.itheima.filter.demo1.FilterDemo1</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterDemo1</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <filter>
    <filter-name>FilterDemo2</filter-name>
    <filter-class>com.itheima.filter.demo1.FilterDemo2</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterDemo2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <filter>

FilterDemo1.java+ FilterDemo2.java+ FilterDemo3.java+demo1.jsp

FilterDemo1.java:
public class FilterDemo1 implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("FilterDemo1 Was created");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("FilterDemo1 Yes");
		//Release
		chain.doFilter(request, response);	
		System.out.println("FilterDemo1 The execution is over");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("FilterDemo1 Destroyed");
		
	}

}




FilterDemo2.java:

public class FilterDemo2 implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("FilterDemo2 Yes");
		//Release
		chain.doFilter(request, response);
		System.out.println("FilterDemo2 The execution is over");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}



FilterDemo3.java:

public class FilterDemo3 implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("FilterDemo3 Yes");
		//Release
		chain.doFilter(request, response);	
		System.out.println("FilterDemo3 The execution is over");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}


demo1.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>dmeo1 page</h1>
<%
   System.out.println("demo1 Yes");
%>
</body>
</html>




5.Filter life cycle

The web server is responsible for the creation and destruction of the filter. When the web application starts, the web server creates an instance object of the filter and calls its init method for initialization (the filter object will be created only once, and the init method will be executed only once)

Every time the filter intercepts, the doFilter method will be executed

When the server is shut down and the application is removed from the server, the server will destroy the Filter object.

6. Overview of filterconfig object

Function: the object used to obtain the related configuration of Filter

method:

Look at the configuration in xml and FilterDemo4.java

public class FilterDemo4 implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//Gets the name of the filter
		String filterName = filterConfig.getFilterName();
		System.out.println("Filter name(filter-name): "+filterName);
		//Get initialization parameters
		String username = filterConfig.getInitParameter("username");
		String password = filterConfig.getInitParameter("password");
		System.out.println("username:"+username);
		System.out.println("password:"+password);
		//Get all parameter information
		Enumeration<String> names = filterConfig.getInitParameterNames();
		while (names.hasMoreElements()) {
			String name =  names.nextElement();
			String value = filterConfig.getInitParameter(name);
			System.out.println(name+"  "+value);
			
		}
		
	}

}

 

7. Relevant configuration of filter

   < URL pattern > configuration

  1. Full path matching           Start with /    E.g. / aaa  
  2. Directory matching                   Start with / end with *     E.g. / aaa/*
  3. Extension matching               Cannot start with / start with *   For example, *. jsp   *. do   

  < Servlet name > configuration

      Intercepting servlet s specifically with their configuration name

  < Dispatcher > configuration

  1. By default, the filter will intercept the request if it is forwarded (this forwarding needs to be intercepted).
  2. Value of Dispatcher

              REQUEST is the default value. The default filter intercepts requests.

              FORWARD forwarding.

              Intercept when the INCLUDE page contains

              The ERROR page is intercepted when the global ERROR page jumps

Tags: Java Back-end servlet filter

Posted on Thu, 25 Nov 2021 19:40:03 -0500 by southofsomewhere