Interview articles - one article to understand filters and interceptors in Java: detailed examples, mastered step by step

1. Filters are the same as interceptors

1. Interceptors and filters both embody the idea of ​​AOP, and the method can be enhanced to intercept the request method.

2. Both interceptors and filters can set the execution order through the Order annotation

Second, the difference between filters and interceptors

In Java Web development, filters (Filter) and interceptors (Interceptor) are common components used to process between requests and responses. Their main differences are as follows:

  1. The running location is different: the filter is a component that runs between the Web server and the Servlet container, and can intercept all requests and responses entering and leaving the container; while the interceptor intercepts specific controller methods, only in the controller Internal execution.
  2. The execution order is different: the execution order of filters is determined by the order in which they are declared in the web. That is to say, the interceptor can specify the sequence.
  3. Different functions: filters are mainly used to preprocess and filter requests, such as setting character sets, login verification, logging and other operations; while interceptors are mainly used to control the process of requests, such as permission verification, parameter injection, exceptions processing etc.
  4. Depending on the framework is different: the filter is implemented based on the Servlet specification and does not depend on any specific framework; while the interceptor is usually implemented for a specific framework or library, such as the interceptor in the Spring MVC framework.

To sum up, filters and interceptors have certain differences in implementation, functions, and usage scenarios. Developers can choose suitable components according to specific needs.

3. Implementation of filters and interceptors

  • Configure the web layer in the filter web.xml

In Java Web development, filters are mainly used to preprocess and filter requests. You can create a custom filter by implementing the javax.servlet.Filter interface. Specific steps are as follows:

  1. Create a Java class that implements the javax.servlet.Filter interface and implements the doFilter() method.
javaCopy code 
public class MyFilter implements Filter { 
    public void init(FilterConfig config) throws ServletException { 
        // filter initialization operation 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException 
        filter processing logic 
        / / Preprocess the request and response 
        // Call the chain.doFilter() method to pass the request to the next filter or Servlet 
        chain.doFilter(request, response); 
        // Post-process the response 
    } 

    public void destroy() { 
        // filter destroy operation 
    } 
}
  1. Declare the filter and specify the URL pattern in the web.xml file.
xmlCopy code
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>com.example.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

In the above code, filter-name specifies the name of the filter, filter-class specifies the implementation class of the filter; filter-mapping specifies the URL pattern to be intercepted by the filter, and /* means to intercept all requests.

  1. Redeploy the web application and start the server to use this filter to preprocess and filter requests.

It should be noted that when implementing a filter, information such as initialization parameters and ServletContext can be obtained through the FilterConfig object, so as to achieve more refined filtering processing. At the same time, in the doFilter() method, the doFilter() method of the FilterChain object needs to be called to pass the request to the next filter or Servlet, otherwise the request will be blocked and cannot be processed normally.

  • Configure the action layer in the interceptor springmvc.xml (between sevlet and controller)

In Java Web development, an interceptor (Interceptor) is a component used to intercept and process requests. A custom interceptor can be created by implementing the HandlerInterceptor interface. Specific steps are as follows:

  1. Create a Java class that implements the HandlerInterceptor interface and overrides its three methods: preHandle(), postHandle(), and afterCompletion().
javaCopy code 
public class MyInterceptor implements HandlerInterceptor { 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 
            throws Exception { 
        // Called before the controller method is executed, returning true means continuing to execute subsequent interceptors and controller methods; returning false Indicates to stop the execution of subsequent interceptors and controller methods. 
        return true; 
    } 

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
            ModelAndView modelAndView) throws Exception { 
        // Called after the controller method is executed and before the view is rendered, the model data can be modified or viewed. 
    } 

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, 
    } 
            Exception ex) throws Exception {
        // Called after the entire request is completed, it can be used to clean up resources and other work. 
}
  1. Declare the interceptor in the Spring MVC configuration file and specify the interception path.
xmlCopy code
<mvc:interceptors>
    <bean class="com.example.MyInterceptor" />
</mvc:interceptors>

In the above XML configuration, MyInterceptor is the custom interceptor class name. By registering the interceptor in the configuration file of Spring MVC, all requests passing through the interceptor path will be intercepted and processed accordingly.

It should be noted that when implementing an interceptor, you can choose which methods need to be rewritten according to your own needs, so as to achieve fine-grained interception processing. At the same time, in the preHandle() method, a boolean type result needs to be returned to indicate whether to continue to execute the subsequent interceptor and controller methods. If false is returned, the request will be stopped and will not continue to execute.

4. Interview questions related to filters and interceptors

  1. What is the difference between filter and interceptor?

Filter (Filter) is a component used to preprocess and filter requests in the Servlet container, and can implement functions such as filtering, verification, and compression. The interceptor (Interceptor) is a component used to intercept and process requests in the Spring MVC framework, and can implement functions such as authority verification, logging, and exception handling. Filters are implemented in the Servlet container, while interceptors are implemented in the Spring MVC framework.

 2. What is the execution order of filters and interceptors?

In a Java web application, the execution order of filters and interceptors is determined by the order in which they are declared in the configuration file. Generally speaking, the filter or interceptor declared first will be executed first, and the filter or interceptor declared later will be executed last.

3. What are the functions of filters and interceptors?

Both filters and interceptors can process and control requests to implement a series of functions, such as request filtering, authentication, data encryption, logging, etc. Filters are mainly used to preprocess and filter requests, while interceptors are mainly used to intercept requests, intercepting and processing before or after the execution of controller methods.

4. What are the usage scenarios of filters and interceptors?

Both filters and interceptors can be used to implement a range of control and management functions. For example, filters can be used in scenarios such as authentication, data encryption and decryption, request filtering and compression; while interceptors can be used in scenarios such as authority verification, logging, and exception handling.

5. How to use filters and interceptors in Java web application?

In Java web applications, to use filters and interceptors, they need to be declared and registered in the configuration file. For filters, it can be done by adding <filter> and <filter-mapping> tags in the web.xml file; for interceptors, it can be done by adding the mvc:interceptors tag in the Spring MVC configuration file. At the same time, when declaring and registering filters and interceptors, you also need to specify their execution order and interception paths and other related information.

Guess you like

Origin blog.csdn.net/citywu123/article/details/130063748