JavaWeb – Filters and Listeners

Table of Contents

1. Overview of filters

1.1. What is a filter?

1.2. Function of filter

1.3. Filter life cycle

1.4. Filter interception path configuration

1.5. Examples

1.5.1. Character encoding

1.5.2. Login code

2. Overview of listeners

2.1. What is a listener?

2.2. Classification of listeners

2.3. Listener life cycle

2.4. Examples


1. Filter Overview

1.1. What is a filter?

Filter Filter is one of the three major components of JavaWeb. The three major components are: Servlet program, Listener, and Filter.

Filter Filter is a JavaEE specification. That is, the interface, its function is: Intercept requests and filter responses.

1.2. The role of the filter

A filter is a tool used to filter or process data. Its function is to select certain content from the original data and remove or hide other unnecessary content from the data. Filters can be applied to various types of data, such as text, images, audio and video, etc.

In computers, filters are commonly used for:

1. Data processing: Data can be processed, filtered, converted, sorted, etc. through filters to meet user needs. For example, using the filter function in Excel is a type of filter.

2. Data security: Filters can be used to detect and prevent malware, viruses, spam and other content that endangers information security from entering the system or network.

3. Network communication: Filters in network communication are commonly used to filter and intercept network data packets to ensure network security.

4. Information retrieval: In search engines, filters can filter out irrelevant results and improve search efficiency and accuracy.

In short, filters are a widely used tool that can help us process various data and information quickly and effectively.

1.3. Filter life cycle

  1. Initialization: Create a Filter instance when the web application starts and call the init method for initialization settings.

  2. Filtering requests: When a user request reaches the web application, the container will call the doFilter method of Filter to process and filter the request.

  3. Forwarding the request: If the Filter forwards the request to another resource (such as a Servlet or JSP), the container pauses the execution of the Filter and forwards the request to the next resource.

  4. Request processing: After the resource executes the request and generates a response, the container will resume the execution of the Filter and call the doFilter method for subsequent processing.

  5. Destruction: When the web application is closed or uninstalled, the container will call the Filter’s destroy method to release resources and perform cleanup operations.

In the above steps, Filter’s init and destroy methods will only be executed once when creating and destroying Filter instances, while the doFilter method will be executed every time a request arrives.

1.4, Filter interception path configuration

The interception path indicates which resources requested by the Filter will be intercepted, and is configured using the @WebFilter annotation. For example: @WebFilter(“Interception path”)

There are four configuration methods for interception paths:

Intercept specific resources: /index.jsp: only access to index.jsp will be intercepted
Directory interception: /user/*: Access to all resources under /user will be intercepted
Suffix name interception: *.jsp: Accessing resources with the suffix name jsp will be intercepted.
Block all: /*: Access to all resources will be blocked
Through the above study of the interception path, you will find that the configuration method of the interception path is the same as the configuration method of the Servlet’s request resource path, but the meaning is different.

1.5, Example

1.5.1, character encoding

We write the CharsetFilter class and set the encoding to UTF-8 in the doFilter() method of the filter.

package com.school.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * Set encoding
 */
@WebFilter("/*")
public class CharsetFilter implements Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
1.5.2, login code

We write the FilterDemo class and set the login judgment in the doFilter() method of the filter.

package com.org.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Login filtering
 */

@WebFilter("/*")
public class FilterDemo implements Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String uri = request.getRequestURI();
        if (uri.contains("login") || uri.contains("Login")){
            filterChain.doFilter(request,response);
        }else {
            HttpSession session = request.getSession();
            String username = (String)session.getAttribute("username");
            if (username == null){
                request.getRequestDispatcher("/loginfail.jsp").forward(request,response);
            }else {
                filterChain.doFilter(request,response);
        }
        }
    }
}

2. Overview of the listener

2.1. What is a listener?

The listener in JavaWeb is an event mechanism that is used to monitor the occurrence of certain events when the application is running. It is usually used for operations such as initialization, destruction, and maintenance.

2.2. Classification of listeners

  1. ServletContextListener (global context listener): Listens to the creation and destruction events of the ServletContext object. It can perform initialization operations when the application starts, such as loading configuration files, etc., and can also perform destruction operations when the application stops.

  2. HttpSessionListener (session listener): Listens to the creation and destruction events of the HttpSession object. It can perform operations at the beginning of the user session, such as creating user login logs, etc., and can also perform cleanup operations at the end of the user session.

  3. ServletRequestListener (request listener): Listens to the creation and destruction events of the HttpServletRequest object, and can perform related operations when each request arrives, such as recording request logs.

2.3. Life cycle of listener

  1. Initialization phase (Initialization): When the container loads a web application, an instance of the listener will be created and its init() method will be called for initialization. Some initialization work can be completed at this stage.

  2. Event Handling: During the running of the web application, when an event occurs, the listener will be triggered and the corresponding callback method will be called to handle the event. For example, the ServletContextAttributeListener listener can monitor changes in the ServletContext attribute. When its attribute value changes, the corresponding callback method will be triggered.

  3. Destroy phase (Destroy): When the web application is closed, the container will call the listener’s destroy() method to destroy the listener instance. Some resource release and other cleanup work can be completed at this stage.

2.4, Example

package com.org.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class VisitorListener implements HttpSessionListener{
    private static long totalCount = 0;
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        totalCount + + ;
        System.out.println("Number of people online:" + totalCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        totalCount--;
    }
}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138353 people are learning the system