springmvc中WebMvcConfigurationSupport中addInterceptor使用详解及方法详解
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                WebMvcConfigurationSupport是Spring MVC框架中提供的一个用于定制Spring MVC配置的类。如果你想要添加自定义拦截器,你可以通过继承WebMvcConfigurationSupport并覆盖其addInterceptors方法来实现。
以下是一个如何使用addInterceptor方法添加自定义拦截器的例子:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.HandlerInterceptor;
 
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
 
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor customInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 在请求处理之前进行调用(Controller方法调用之前)
                return true; // 如果返回false,则停止流程,api不会被调用
            }
 
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
            }
 
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                // 在整个请求结束之后调用,也就是在DispatcherServlet渲染了视图执行
            }
        };
 
        registry.addInterceptor(customInterceptor)
                .addPathPatterns("/**"); // 添加拦截路径
                //.excludePathPatterns("/login", "/error"); // 添加排除路径
    }
}在这个例子中,我们定义了一个customInterceptor,它实现了HandlerInterceptor接口。然后我们将其注册到Spring MVC配置中,并指定所有路径/**都将被这个拦截器拦截。你也可以通过excludePathPatterns方法排除特定的路径。这样,每次请求/**路径时,都会先执行customInterceptor中的方法。
评论已关闭