Spring Boot2 Interceptor

170 阅读1分钟

All HandlerMapping implementations support handler interceptors that are useful when you want to apply specific functionality to certain requests — for example, checking for a principal. Interceptors must implement HandlerInterceptor from the org.springframework.web.servlet package with three methods that should provide enough flexibility to do all kinds of pre-processing and post-processing:

  • preHandle(..): Before the actual handler is executed
  • postHandle(..): After the handler is executed
  • afterCompletion(..): After the complete request has finished.

The preHandle(..) method returns a boolean value. You can use this method to break or continue the processing of the execution chain.

image-20210503022241072.png

MyInterceptor

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor preHandle....");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor postHandle....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor afterCompletion....");
    }
}

Register interceptors to apply to incoming requests.

import com.kenny.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/","/css/**","/js/**","/image/**");
    }
}

The following example shows how to achieve the same configuration in XML:

<mvc:interceptors>
  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> 
  <mvc:interceptor> 
      <mvc:mapping path="/**"/> 
      <mvc:exclude-mapping path="/admin/**"/> 
      <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/> 
    </mvc:interceptor> 
    <mvc:interceptor>
        <mvc:mapping path="/secure/*"/>
        <bean class="org.example.SecurityInterceptor"/>   
    </mvc:interceptor> 
</mvc:interceptors>