Springboot 搭建拦截器

1、先建包com.shishike.susie.interceptor

2、新建类

package com.shishike.susie.interceptor;

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

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

public class MyInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.printf("afterCompletion被调用");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.printf("postHandle被调用");
	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		System.out.printf("preHandle被调用");
        return true;    //如果false,停止流程,api被拦截
	}

}

3、启动类中设置拦截器和拦截路径

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.shishike.susie.interceptor.MyInterceptor;

@EnableAutoConfiguration
@ComponentScan(basePackages={"com.shishike.susie"})
@MapperScan("com.shishike.susie.dao")//将项目中对应的mapper类的路径加进来就可以了
public class Application {
	 public static void main(String[] args) throws Exception {
		    SpringApplication.run(Application.class, args);
		    }
	 
	//mvc控制器
	@Configuration
	static class WebMvcConfigurer extends WebMvcConfigurerAdapter{
	     //增加拦截器
	    public void addInterceptors(InterceptorRegistry registry){
	         registry.addInterceptor(new MyInterceptor())    //指定拦截器类
	                 .addPathPatterns("/**");        //指定该类拦截的url,这种写法表示拦截所有请求
	     }
	}
}

4、出错的地方

     拦截路径写错,导致拦截不到      

 registry.addInterceptor(new MyInterceptor())    //指定拦截器类
	                 .addPathPatterns("/");        //指定该类拦截的url

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值