Spring MVC 中 Interceptor 的浅显用法

应用:对于某些url 执行拦截 验证。

  • 1、书写 HandlerInteceptor 的实现类

Intercept the execution of a handler. Called after HandlerMapping determined an appropriate handler object, but before HandlerAdapter invokes the handler.DispatcherServlet processes a handler in an execution chain, consisting of any number of interceptors, with the handler itself at the end.With this method, each interceptor can decide to abort the execution chain,typically sending an HTTP error or writing a custom response.

@Slf4j
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("########请求URI为{}",request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
  • 2、将该实现类注册进InterceptorRegistry

方式:

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

所以 我们应该书写自己的配置类 @Configuration 同时实现 WebMvcConfigur或者如下 定义组件并被容器管理

@Configuration
public class MyConfig {
    /**
     * 定制spring mvc
     * @return
     */
    @Bean
    public WebMvcConfigurer getWebMvcConfigurer (){
        WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
            }
        };
        return webMvcConfigurer;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值