如何使用攔截器Interceptor
回顧一下:springMVC時怎麼用?自己寫個Interceptor,繼承HandlerInterceptor
然後在xml中配置
springboot使用攔截器,方法差不多:
第一步:定義一個攔截器
public class AccessInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("進入 AccessInterceptor");
return true;//傳回true表示放行
}
第二步:配置(@Configuration)該攔截器
@Configuration//表示這是一個配置,springboot,麻煩你讀取這個配置
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//定義要攔截的路徑
String[] addPathPatterns= {"/add"};
//定義不攔截的路徑
String[] excludePathPatterns= {"/update"};
registry.addInterceptor(new AccessInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
//registry.addInterceptor(new AccessInterceptor()).addPathPatterns("/add").excludePathPatterns("/update");
}
第三步:測試即可
http://localhost:8080/update 不攔截
http://localhost:8080/add 攔截
@RestController
public class UserController {
@GetMapping("add")
public String add()
{
return "add";
}
@GetMapping("update")
public String update()
{
return "update";
}
}