SpringBoot中拦截器的配置(十四)

项目结构:

1)先写一个Controller类

@Controller
public class TestHelloController {
    @RequestMapping("/testInterceptor")
    @ResponseBody
    public String testInterceptor() {
        return "interceptorController";
    }
}

 2)写一个Interceptor拦截器类,其中继承HandlerInterceptorAdapter类,并重写其方法。

public class MyInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor`````");
        return true;
    }

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

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    }
}

3)Config配置类中注册拦截器

以前在springmvc的xml文件注册方式是

    <!-- 注册拦截器 -->
	<mvc:interceptors>
	   <mvc:interceptor>
	      <mvc:mapping path="/**"/>
	      <!-- 此路径不拦截 -->
	      <mvc:exclude-mapping path="/method2"/>
	      <bean class="com._520it.SpringIntercept"></bean>
	   </mvc:interceptor>
	</mvc:interceptors>

现在改为Config类中注册:

@SpringBootApplication
public class AppConfig  extends WebMvcConfigurerAdapter {
    public static void main(String[] args) {
        SpringApplication.run(AppConfig.class, args);
    }

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration ir =registry.addInterceptor(myInterceptor());
        ir.addPathPatterns("/*");
    }

    //建立拦截器对象到Spring容器中
    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值