The difference between filter and interceptor

filter:

It is only called once in the initialization, and then the monitoring is started, and all requests under the corresponding path will be filtered and processed (filtered url, filter parameters)

 

Interceptor:

aop is woven into the action method

 

Filter ( filter ), the filter is between the client and the web resource (Servlet, JSP, HTML), and the request and response between the client and the web resource must be filtered by the filter. For example: if the address of 192.10.10.1 is prohibited from being accessed in the filter, then when the client sends a request to access 192.10.10.1, after the filter, the client will get a response indicating that the IP is prohibited from accessing. In java web, you pass in the request and response to 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, such as filtering out illegal url (not the address request of login.do , if the user is not logged in, it will be filtered out), or set the character set uniformly before the action of the incoming servlet or struts, or remove some illegal characters

      Interceptor ( interceptor ), interceptor is a kind of aspect-oriented/aspect-oriented programming (AOP Aspect-Oriented Programming), and aspect-oriented is to separate the general services of multiple modules, such as permission management, log service, they are in multiple Modules will be used, you can encapsulate each of them as a reusable module. The specific implementation of these general services is completed by interceptors. For example, when a user client accesses some confidential modules, it should first pass a permission review interceptor to conduct permission review, and determine whether the user has the permission to perform the operation. . Aspect-oriented programming is to call a method before your service or a method, or call a method after the method. For example, a dynamic proxy is a simple implementation of an interceptor that prints a string (or does other business) before you call the method. Logical operations), you can also print out strings after you call a method, or even do business logic operations when you throw an exception.

 

The difference between interceptor and filter :

1. The interceptor is based on the reflection mechanism of java , while the filter is based on the function callback

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. Interceptors can access objects in the action context and value stack, while filters can not

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

 

 Execution order : before filtering - before intercepting - action processing - after intercepting - after filtering. I personally think that filtering is a horizontal process. First, filter the content submitted by the client (for example, the processing that users who are not logged in cannot access internal pages); after the filtering is passed, the interceptor will check the verification of the data submitted by the user, and 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 to the subsequent operations of the filter.

 

 Details :

 Interceptor: Aspect-oriented programming is to call a method before your service or a method, or call a method after the method. For example, a dynamic proxy is a simple implementation of an interceptor that prints out a string before you call the method (or Do other business logic operations), you can also print out a string after you call the method, or even do business logic operations when you throw an exception.
Let's take a look at the difference between filters and interceptors through examples:
Use interceptors to filter jsp pages in the /admin directory
<package name="newsDemo" extends="struts-default"
        namespace="/admin">
        <interceptors>
            <interceptor name="auth" class="com.test.news.util.AccessInterceptor" />
            <interceptor-stack name="authStack">
                <interceptor-ref name="auth" />
            </interceptor-stack>
        < /interceptors>
        <!-- action -->
        <action name="newsAdminView!*"

            <interceptor-ref name="defaultStack"/>
            <interceptor-ref name="authStack">
            </interceptor-ref>
下面是我实现的Interceptor class:
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 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, such as filtering out illegal urls (not login. do address requests, if the user is not logged in, they will be filtered out), or uniformly set the character set before the action of the incoming servlet or struts, or remove some illegal characters.
Use the filter to filter the jsp pages in the /admin directory, first Filter configuration in web.xml:
    <filter>
        <filter-name>access filter</filter-name>
        <filter-class>
             com.test.news.util.AccessFilter
        </filter-class>
    </filter>
    < filter-mapping>
        <filter-name>access filter</filter-name>
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>
The following is the implementation class for filtering:
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 {
     }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326603090&siteId=291194637