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