Distinguish between Java interceptors and filters

Reading guideToday, I'll take you to analyze the difference between java interceptors and filters. The article has a very detailed explanation, which is very helpful to the little friends who are learning java. If you need it, you can refer to it

1, filter

The filter is between the client and the web resource (servlet, JSP, HTML), the request and response between the client and the web resource should be filtered through the filter. For example, if the filter defines the address of prohibiting access to 192.10.10.1, when the client sends a request to access 192.10.10.1, after passing through the filter, the client will get a prompt that the IP is prohibited from access. In java web, you can send The incoming request and response filter out some information in advance, or set some parameters in advance, and then pass in the action of servlet or struts for business logic, For example, filter out the illegal url (not the address request of login.do, if the user does not log in), or uniformly set the character set before passing in the action of servlet or struts, or remove some illegal characters

2, interceptor

Interceptors are aspect / aspect oriented programming (AOP aspect oriented programming), and aspect oriented is to separate the general services of multiple modules, such as permission management and log service. They will be used in multiple modules, so they can be encapsulated into a reusable module. The specific implementation of these general services is completed through interceptors. For example, the user client should access some confidential modules First, conduct permission review through the interceptor of permission review to determine whether the user has the permission of this operation before downward execution. In aspect oriented programming, you call a method before your service or a method, or call a method after the method, for example, the dynamic proxy is the simple implementation of the interceptor. Print the string before you call the method (or do other business logic operations), or print the string after you call the method, or even do business logic operations when you throw an exception.

3, The difference between interceptor and filter

1. Interceptors are based on java's reflection mechanism, while filters are based on function callbacks (responsibility chains)

2. The filter depends on the servlet container, while the interceptor does not depend on the servlet container

3. Interceptors can only work on action requests, while filters can work on almost all requests

4. The interceptor can access the object in the action context and value stack, but the filter cannot

5. In the life cycle of an action, interceptors can be called multiple times, while filters can only be called once when the container is initialized

Execution sequence: before filtering - before intercepting - Action processing - after intercepting - after filtering. Personally, I think filtering is a horizontal process. First, filter the content submitted by the client (for example, the processing that the unlisted user cannot access the internal page); After the filtering is passed, the interceptor will check the verification of the data submitted by the user, do some preliminary data processing, and then send the processed data to the corresponding Action; After the Action processing is completed and returned, the interceptor can also do other processes (I haven't thought of what to do), and then return upward to the subsequent operations of the filter.

4, Detailed description

Interceptor: in the face oriented programming is to call a method before your service or a method, or to call a method after the method, for example, the dynamic proxy is the simple implementation of the interceptor. Print the string before you call the method (or do other business logic operations), or print the string after you call the method, or even do business logic operations when you throw an exception.

Let's take a look at the differences between filters and interceptors through examples:
Use the interceptor to filter jsp pages in the / admin directory

Here is the Interceptor class I implemented:

package com.test.news.util;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.test.news.action.AdminLoginAction;
/**
* @author chaoyin
*/
public class AccessInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = -4291195782860785705L;
    
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
         
         ActionContext actionContext = actionInvocation.getInvocationContext();
         Map session = actionContext.getSession();
      
        //except login action
         Object action = actionInvocation.getAction();
        if (action instanceof AdminLoginAction) {
            return actionInvocation.invoke();
         }
        //check session
        if(session.get("user")==null ){
            return "logout";
         }
        return actionInvocation.invoke();//go on
     }
}

Filter: in the java web, the request and response you pass in filter out some information in advance, or set some parameters in advance, and then pass in the action of servlet or struts for business logic, For example, filter out the illegal url (not the address request of login.do, if the user does not log in), or uniformly set the character set before passing in the action of servlet or struts, or remove some illegal characters

Use the filter to filter jsp pages under the / admin directory. First, on the web XML filter configuration:
The following is the filter implementation class:

package com.test.news.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AccessFilter implements Filter {
/**
* @author chaoyin
*/
  
    public void destroy() {
    
     }
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
             FilterChain filterChain) throws IOException, ServletException {
             
         HttpServletRequest request = (HttpServletRequest)arg0;
         
         HttpServletResponse response = (HttpServletResponse)arg1;
         
         HttpSession session = request.getSession();
         
        if(session.getAttribute("user")== null && request.getRequestURI().indexOf("login.jsp") ==-1 ){
             response.sendRedirect("login.jsp");
            return ;
         }
         
         filterChain.doFilter(arg0, arg1);
     }
    public void init(FilterConfig arg0) throws ServletException {
    
     }
}

This is the end of this article on the analysis of the differences between Java interceptors and filters That's how Linux should learn

Added by Popcorn on Tue, 04 Jan 2022 07:04:34 +0200