Filter and Listener

Filter

What is a filter

A filter is essentially an intercept of web resources, a process that is done, then handed over to the next filter or servlet, usually a to intercept request s for inbound processing, or an intercept process for returned response s

Filter Grammar Format

  • 1. Create a class implementation interface
public class SignInFilter implements Filter{}
  • 2. Override methods in interfaces
/*Initialize method to receive parameters of FilterConfig type This parameter is some configuration of Filter*/
 public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter Initialization");
    }

/*Filtering is primarily about processing request s and response s and then handing them down to a filter or a Servlet*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter for processing");
    }

/*destroy-method*/
 public void destroy() {
        System.out.println("Filter destroyed");
    }
  • 3. Configure in the web.xml file
    <filter>
        <filter-name>Filter Name</filter-name>
        <filter-class>
            Path where filter is located
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Filter Name</filter-name>
        <url-pattern>Resources that need to be filtered</url-pattern>
    </filter-mapping>

Prevent users from not logging on to the post-logon page through a filter

Configuration in the web.xml file is replaced by annotations here

@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("Filter start operation");
        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("Filter End");
    }

    @Override
    public void destroy() {
        System.out.println("Filter destroyed");
    }
}

Monitor

What is a listener

A listener is a component that listens for state changes of a domain object

Concepts related to listeners:

  • Event source: The object being listened on (request, session, servletContext for the three domain objects)
  • Listener: Listening for changes in the state of event source objects triggers the listener
  • Register listeners: Bind listeners to event sources
  • Response_is: Functional code involved in the listener listening for state changes of event sources (programmer writing code)

Listener Classification

First dimension

By the objects being listened on: ServletRequest domain, HttpSession domain, ServletContext domain

Second Dimension

By what you listen for: listening for creation and destruction of domain objects, listening for property changes of domain objects

\ServletContext DomainHttpSession DomainServletRequest Domain
Creation and Destruction of Domain ObjectsServletContextListenerHttpSessionListenerServletRequestListener
Changes in attributes within domain objectsServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener

A listener that monitors the creation and destruction of objects in three domains

Writing steps for listeners

1. Write listener classes to implement listener connection
2. _method of covering the listener
3. Require Configuration - Registration in web.xml

Example

Listen for session creation and destruction
Configuration in the web.xml file is replaced by annotations here

@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
A listener that listens for creation and destruction of ServletContext domains

_Life Cycle of Servlet Domain
When to create: Server starts creating
When to destroy: Server shutdown destroys

Main work of the ServletContextListener listener
Initialization: Initialization of objects, Initialization of data (loading database drivers, initialization of connection pools), Loading of some initialization configurations (spring configurations), Task Scheduling (Timer/TimerTask)

HttpSessionListener
Listeners listening for creation and destruction of Httpsession domains

_life cycle of HttpSession object
When to create: Created on second key request.getSession
When to destroy: server shutdown destroys, session expires (default 30 minutes, modify default 30 minutes is web.xml in Tomcat, modify current item_expires in web.xml of item), dynamic destroy

The main work of the HttpSessionListener listener is:
Because the session object is created by default every time a station is visited (the session attribute in the page directive in jsp_defaults to true, that is, session is created when it is accessed), it can be used to count the number of visited sessions

ServletRequestListener
Listener to create and destroy ServletRequest domain

Keywords: Java servlet mvc

Added by classix16 on Wed, 29 Sep 2021 20:29:55 +0300