使用注解@Configuration 配置拦截器
继承WebMvcConfigurerAdapter
重写addInterceptoers 添加需要的拦截器地址
文件目录如下:
- Interceptor.java
- ItemController
- UserController.java
- WebMain.java
- WebMvcConfigurer
Interceptor.java
public class Interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map<String,String[]> param = request.getParameterMap();
if(param.get("id") == null){
throw new Exception("missing parameter id");
}
return true;
}
}
ItemController.java
@RestController
@RequestMapping("/service/item")
public class ItemController {
@GetMapping("/getItem")
public String getItem() {
return "商品详情";
}
}
UserController.java
@RestController
@RequestMapping("/service/user")
public class UserController {
@GetMapping("/visit")
public String login() {
return "游客访问";
}
}
WebMain.java
@SpringBootApplication
public class WebMain {
public static void main(String[] args) {
SpringApplication.run(WebMain.class, args);
}
}
WebMvcConfigurer.java
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Bean
public Interceptor getInterceptor(){
return new Interceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry){
//可以添加多个拦截器,拦截顺序是添加顺序
registry.addInterceptor(getInterceptor()).addPathPatterns("/service/item/**");
super.addInterceptors(registry);
}
}