Simple principles and differences of Java interceptors, filters, and listeners

Keywords: Java Spring Struts

1. Interceptor concepts

Interceptors in java are objects that dynamically intercept action calls, providing a mechanism for developers to execute a piece of code before and after an action is executed, or within an Action

Blocking execution before execution also provides a way to extract reusable parts of code in an Action. In AOP, interceptors are used to intercept a method or field before it is accessed

At present, the main thing we need to know is Spring's interceptor, Struts2's interceptor doesn't need to go into it.

2. Interceptor principles

Most of the time, interceptor methods are invoked through proxy. The interceptor implementation for Struts2 is relatively simple. When a request reaches the ServletDispatcher for Struts2, Struts2

The interceptor for Struts2 is available.

Interceptors are an implementation of AOP. The Struts2 Interceptor Stack is a chain of interceptors in a certain order. When accessing intercepted methods or fields, the Struts2 Interceptor Chain

Interceptors in will be invoked in the order previously defined.

3. Steps to customize interceptors

Step 1: Customize a class that implements the Interceptor interface, or inherit the abstract class AbstractInterceptor.

Step 2: Register the defined interceptor in the configuration file.

Step 3: Reference to the above-defined interceptors in the Action is required. For convenience, the interceptor can also be defined as the default interceptor, so that all the interceptors without special instructions

Action s are blocked by this interceptor.

4. The difference between filter and interceptor

Filters can simply be interpreted as "take what you want", and filters focus on web requests; interceptors can simply be interpreted as "reject what you want", and interceptors focus on method calls, such as interception

Sensitive vocabulary.

4.1, interceptors are based on java reflection mechanism, while filters are based on function callbacks. (Some people say interceptors are based on dynamic proxies.)

4.2, the interceptor does not depend on the servlet container, and the filter depends on the servlet container.

4.3 Interceptors only work on Action s, and filters work on all requests.

4.4 Interceptors can access objects in the Action context and value stack, but filters cannot.

4.5 During the life cycle of an Action, the interceptor can be called multiple times, while the filter can only be called once when the container is initialized.

5, Spring Interceptor

5.1, abstract class HandlerInterceptorAdapter

If we use the Spring framework in our project, we can inherit it directly
HandlerInterceptorAdapter.java is an abstract class that implements our own interceptors.

The Spring framework wraps java's interceptor concept much like Struts2. The HandlerInterceptor Adapter inherits the abstract interface HandlerInterceptor.

package org.springframework.web.servlet.handler;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.web.servlet.HandlerInterceptor;  
import org.springframework.web.servlet.ModelAndView;  
public abstract class HandlerInterceptorAdapter implements HandlerInterceptor{  
    // Called before the business processor processes the request  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{  
        return true;  
    }  
    // Execute after the business processor has processed the request, before generating the view  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  
      throws Exception{  
    }  
    // Called after Dispatcher Servlet has fully processed the request and can be used to clean up resources  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  
      throws Exception{  
    }  
}  

Next let's look at a simple interceptor implemented by the Spring framework
UserRoleAuthorizationInterceptor, inherited by UserRoleAuthorizationInterceptor

The abstract class HandlerInterceptorAdapter, which implements the interception function of user login authentication, will report 403 errors if the current user is not authenticated.

package org.springframework.web.servlet.handler;  
import java.io.IOException;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter{  
    // String array to hold user role information  
    private String[] authorizedRoles;  
    public final void setAuthorizedRoles(String[] authorizedRoles){  
        this.authorizedRoles = authorizedRoles;  
    }  
    public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  
      throws ServletException, IOException{  
        if (this.authorizedRoles != null) {  
            for (int i = 0; i < this.authorizedRoles.length; ++i) {  
                if (request.isUserInRole(this.authorizedRoles[i])) {  
                    return true;  
                }  
            }  
        }  
        handleNotAuthorized(request, response, handler);  
        return false;  
    }  
    protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler)  
      throws ServletException, IOException{  
          // 403 means the resource is unavailable. The server understands the user's request but refuses to process it, usually due to permission issues  
          response.sendError(403);  
    }  
}  

Below, we use the Handler Interceptor Adapter provided by the Spring framework to pull classes to implement a custom interceptor. This interceptor is called


UserLoginInterceptorBySpring for login interception control. The workflow is as follows: if the current user is not logged in, jump to the login page; if the login is successful, jump to

URL page previously visited.

import java.util.HashMap;  
import java.util.Map;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.web.servlet.ModelAndView;  
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;  
/** 
 * @description Implement a custom interceptor using the Handler Interceptor Adapter provided by the spring framework 
 */  
public class UserLoginInterceptorBySpring extends HandlerInterceptorAdapter{  
    // Called before the business processor processes the request  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{  
        // What is the difference between equals IgnoreCase and equals?  
        if("GET".equalsIgnoreCase(request.getMethod())){  
            //RequestUtil.saveRequest();  
        }  
        System.out.println("preHandle...");  
        String requestUri = request.getRequestURI();  
        String contextPath = request.getContextPath();  
        String url = requestUri.substring(contextPath.length());  
        System.out.println("requestUri" + requestUri);  
        System.out.println("contextPath" + contextPath);  
        System.out.println("url" + url);  
        String username = (String) request.getSession().getAttribute("username");  
        if(null == username){  
            // Jump to the login page  
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);  
            return false;  
        }  
        else{  
            return true;  
        }  
    }  
    // Execute after the business processor has processed the request, before generating the view  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{  
        System.out.println("postHandle...");  
        if(modelAndView != null){  
            Map<String, String> map = new HashMap<String, String>();  
            modelAndView.addAllObjects(map);  
        }  
    }  
    // Called after Dispatcher Servlet has fully processed the request and can be used to clean up resources  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{  
        System.out.println("afterCompletion...");  
    }  
}  

Interceptors are implemented by Java reflection mechanisms. The implementation of interceptors uses dynamic proxies implemented by JDK, which we all know depends on interfaces.

Used in facet-oriented programming, where a method is called before or after your service or a method. Interceptors are not in web.xml, such as struts in

Configuration in struts.xml.

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    
    Object result = null;    
    System.out.println("Before a method call, you can execute a piece of code" + method.getName());    
    result = method.invoke(this.targetObj, args);    
    System.out.println("After a method call, you can execute a piece of code " + method.getName());    
    return result;    
}    

Summary:

1. Filter: As the name implies, a filter is used to filter. A Java filter can provide us with system-level filtering, that is, it can filter all web requests.

In Java Web, your incoming request,response, filters out some information in advance, or sets some parameters in advance, then passes in a servlet or

Struts'action s perform business logic, such as filtering out illegal URLs (not address requests for login.do, if the user is not logged in), or passing in servlet s or struts

Set the character set uniformly before the action, or remove some illegal characters (chat rooms often use, some abusive words). The filter process is linear, after the url comes in, after the check,

It keeps the original process running down and is received by the next filter, servlet.

2.Listener: A Java listener, also a system-level listener. A listener starts when a web application starts. Java listeners are often used in c/s mode, which

A process is generated for a particular event. Listening is used in many modes, such as the observer mode, which is achieved by using a listener, such as counting the number of people online on a website.

For example, struts2 can be started by listening. Servlet listeners are used to listen for important events, and listener objects can do some necessary processing before and after the events occur.

3. Interceptor: Interceptors in java provide non-system-level interception, that is, they are less powerful than filters in terms of coverage, but more targeted.

Interceptors in Java are based on the Java reflection mechanism. A more accurate partition should be a dynamic proxy based on JDK implementation. It depends on specific interfaces to generate byte codes dynamically at run time.

Interceptors are objects that dynamically intercept Action calls and provide a mechanism for developers to execute a piece of code before and after an Action is executed, or to block an Action before it is executed.

In AOP, interceptors are used to intercept a method or field before it is accessed, and then before or

The java interceptor is mainly used in plug-ins, extensions such as Hibernate Spring Struts2, a bit like slice-oriented technology, before using it

Thank you for reading. If you find this article helpful, remember to give a compliment before you go.

 

Posted by gabrielserban on Thu, 07 Oct 2021 17:49:30 -0700