SoFunction
Updated on 2025-04-13

Definition and configuration process of Spring MVC interceptor

1. Components in SpringMVC: Interceptor

Interceptor

It is very practical for us and is often used.Can intercept before and after all HandlerMapping, when weWhen a specific function needs to be applied to a request that complies with a certain rule, you can use the interceptor at this time.

Our custom interceptor must be inherited,existHandlerInterceptorBy three default methods

package ;

import ;
import ;

import ;
import ;

public interface HandlerInterceptor {
	/**
	 * Before executing the actual memory program, determine whether to release it based on the returned boolen
	 */
	default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		return true;
	}
	/**
	 * After executing the handler
	 */
	default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
	}
	/**
	 *After completing the request
	 */
	default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}

}

Custom interceptors

package ;

import ;
import ;

import ;
import ;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = ();
        ("Requested path:" +requestURI);
        long startTime = ();
        ("request::start",startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (long)("request::start");
        long processEndTime = ();
        ("Time to complete the process execution:"+ (processEndTime-startTime) + "millisecond");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime = (long)("request::start");
        long endTime = ();
        ("Time to complete the response from request to completion:"+ (endTime-startTime) + "millisecond");
    }
}

2. Interceptor configuration

After the custom interceptor is completed, we configure our interceptor in Spring MVC, which can be passedHow to configure Java classesConfigure it, you can also useThe way of xml fileMake configuration.

Let's first look at the Java configuration class method

  • @EnableWebMvc: Indicates the ability to enable Spring MVC
  • @Configuration: Indicates that this class is a configuration class in Spring
  • The intercepted configuration needs to be rewriteWebMvcConfigurerofaddInterceptors(InterceptorRegistry registry)Method, byregistryAdd (default intercepts all)
  • Can be passedaddPathPatternsTo indicate which requests are intercepted
  • Can be passedexcludePathPatternsWhich requests are not intercepted

For URI matching patterns:

  • : Match a character
  • *: Match zero or more characters in the path segment
  • **: Match zero or multiple path segments
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	(new MyInterceptor())
        (new LocaleChangeInterceptor());
        (new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
        (new SecurityInterceptor()).addPathPatterns("/secure/*");
    }
}

Configure in xml

<mvc:interceptors>
	<bean class=""/>
    <bean class="."/>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <mvc:exclude-mapping path="/admin/**"/>
        <bean class=""/>
    </mvc:interceptor>
    <mvc:interceptor>
        <mvc:mapping path="/secure/*"/>
        <bean class=""/>
    </mvc:interceptor>
</mvc:interceptors>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.