Filter, listener, interceptor

Connection among filter, listener and interceptor

 

Filter

Mainly used to preprocess user's request

Through Filter technology, we can manage all resources of Web server (such as jsp, html, static resource file, etc.) and intercept them, so as to realize some special functions (such as implementing URL level access control, filtering inscriptions, setting character set encoding format, etc.).

Function realization:

  • Before HttpServletRequest arrives at the Servlet, block the customer's HttpServletRequest request (check or modify its data).
  • Intercept the HttpServletResponse request (check or modify its data) before the HttpServletResponse reaches the client.

How to achieve:

  1. Write a Java class to implement the Filiter interface, and implement the doFilter() method
  2. Register the Filter class written in web.xml

Example: (unified setting of character encoding format utf-8 for request to solve the problem of garbled code)

1. Create a project - filter, add framework support

2. Create a package -- cn.zero.servlet, and write a MyServlet

package cn.zero.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//Servlet needs to inherit HttpServlet interface
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Hello, the world!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

}

3. Configure servlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--To configure servlet-->
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>cn.zero.servlet.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>

4. Configure tomcat, start the project, run: http://localhost:8080/hello

We found that the page has the situation of disorderly code. In order to solve this problem, we need to set the character encoding format in the request to solve this kind of problem.

req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("Hello, the world!");

This will solve the problem of random code!

However, we have multiple methods. If there is a possibility of garbled code, we need to add the above code repeatedly. As time goes by, the code will become more onerous and redundant. Is there a way to solve this kind of problem?

Yes, use interceptor!!!

5. Create package -- cn.zero.filter, and write MyFilter

package cn.zero.filter;

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

//Implement the Filter interface
public class MyFilter implements Filter {

    //1. Filter initialization
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filiter Initialization complete!");
    }

    //Filter performs filtering operation
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        System.out.println("Before filter execution--before");
        chain.doFilter(req, resp); // The doFilter filter operation obtains the request, and then throws the request
        System.out.println("After filter execution--after");
    }

    //3. Filter destruction
    public void destroy() {
        System.out.println("Filter Destroy!");
    }

}

6. Modify the web.xml file and add the filter configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--To configure servlet-->
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>cn.zero.servlet.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <!--To configure filter-->
    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>cn.zero.filter.MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

When configuring the filter, set the URL pattern to: / *, so all requests will be executed through the methods in the cn.zero.filter.MyFilter class!

7. Configure tomcat, start the project again, and run: http://localhost:8080/hello

In this way, our additional interceptors are working!

 

Listener

It is used to monitor the creation, destruction, addition, modification and deletion of some objects and information in web applications, and then make corresponding response processing. When the state of the scope object changes, the server automatically calls the methods in the listener object.

It is often used to count the number of people and users online, initialize the information when the system is loaded, and count the visits to the website.

Example: (use listener to count the number of people online)

Implementation principle: whenever there is an access connection to the server, the server will create a session to manage the session, so we can count the number of online people by the number of sessions.

1. Create a project - listener, add framework support

2. Create package cn.zero.listener and write MyListener class

package cn.zero.listener;

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

//Realize the HttpSessionListener interface, and understand the listener through the session session
public class MyListener implements HttpSessionListener {

    /**
     * We use the number of online visitors to do Demo
     * When creating a session, onLine+1
     * When destroying a session, onLine-1
     */

    //When the session is created, the method is executed
    //It also proves that when the program creates a session, it is monitored by the listener
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();
        //onLine people onLine
        Integer onLine = (Integer) sc.getAttribute("onLine");
        if (onLine == null) {
            onLine = 1;
        } else {
            onLine = onLine + 1;
        }
        sc.setAttribute("onLine", onLine);
    }

    //When the session is destroyed, the method is executed
    //It also proves that when the program destroys the session, it is monitored by the listener
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();
        //onLine people onLine
        Integer onLine = (Integer) sc.getAttribute("onLine");
        if (onLine == null) {
            onLine = 0;
        } else {
            onLine = onLine - 1;
        }
        sc.setAttribute("onLine", onLine);
    }

}

3. Write index.jsp page content

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
  <title>Test the number of people online Demo--listener</title>
</head>
<body>

    <p>
      Current common<%=request.getSession().getServletContext().getAttribute("onLine") %>People online<br>
    </p>

</body>
</html>

4. Configure listener in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <listener>
        <listener-class>cn.zero.listener.MyListener</listener-class>
    </listener>

</web-app>

5. Configure tomcat, publish project, access path: http://localhost:8080/ Using different browsers to access, you can find the increase in the number of session s.

 

Interceptor (Interceptor)

Implement the relevant business processing before and after each request processing.

Based on the implementation of Java reflection mechanism, the intercepted object can only be the class that implements the interface, but can't intercept links like URLs.

The interceptor in Java is an object that dynamically intercepts Action calls. It provides a mechanism for developers to execute a section of code before and after an Action is executed, or to prevent the execution of an Action before it is executed, and also provides a way to extract reusable part of the code in an Action.

In Aop, interceptors are used to intercept a method or field before it is accessed, and then add some operations before and after it.

Example:

1. Create project -- interceptor, create package cn.zero.interceptor

2. Write the interface InterDao, and implement the interface with InterDaoImpl

package cn.zero.interceptor;

public interface InterDao {

    //Execute processing business
    void doSomething();

}
package cn.zero.interceptor;

public class InterDaoImpl implements InterDao {

    //Execute processing business
    public void doSomething() {
        System.out.println("Deal with business!");
    }

}

3. Custom Interceptor

package cn.zero.interceptor;

//custom interceptor 
public class Interceptor {

    //Pre execution method of interceptor
    public void before() {
        System.out.println("Before interceptor execution--before");
    }

    ////Method after interceptor execution
    public void after() {
        System.out.println("After interceptor execution--after");
    }

}

4. Create interceptor proxy object

package cn.zero.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//Interceptor proxy object
public class InterceptorProxy {

    //Represented object
    private Object target;

    //Instantiate an interceptor object
    Interceptor interceptor = new Interceptor();

    //Dynamically generate a proxy object and bind the proxied class and the proxy processor
    public Object getProxyInstance(final Object target) {

        this.target = target;

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        interceptor.before();
                        Object object = method.invoke(target, args);
                        interceptor.after();

                        return object;
                    }
                });
    }

}

5. Write startup class and test run

package cn.zero.interceptor;

public class InterceptorMain {

    public static void main(String[] args) {

        //Create dynamic agent tool
        InterceptorProxy interceptorProxy = new InterceptorProxy();

        //Create business components
        InterDao interDao = new InterDaoImpl();

        //Get proxy object
        InterDao proxy = (InterDao) interceptorProxy.getProxyInstance(interDao);

        //Calling target object methods through proxy objects
        proxy.doSomething();

    }

}

6. View the operation results on the console

We see that when we execute the target method doSomething(), we can increase the business we need before and after it through interceptors!

 

Published 5 original articles, won praise 2, visited 254
Private letter follow

Tags: xml Session JavaEE Java

Posted on Tue, 17 Mar 2020 04:13:08 -0400 by abushahin