在 Spring Boot 控制器类中,暴露了 2 个 API。我有一个要求,只拦截其中的 1 个 API,并且不应该拦截其他 API。请问有人可以帮忙如何实现吗?
以下是代码:
public class HeaderValidationInterceptor extends HandlerInterceptorAdapter{
private static final Logger logger = Logger.getLogger(HeaderValidationInterceptor.class);
//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
validateHeaderParam(request);
request.setAttribute("startTime", startTime);
return true;
}
}
我有一个配置类来添加拦截器,如下所示:
此外,我还有一个配置类来添加拦截器,如下所示:
Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
HeaderValidationInterceptor headerValidationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(headerValidationInterceptor)
}
}
控制器类
@RestController
public class MyController {
@Autowired
private ICityService cityService;
@GetMapping(value = "/cities")
public List<City> getCities() {
List<City> cities = cityService.findAll();
return cities;
}
@GetMapping(value = "/cities/{cityId}")
public City getCityById(@PathVariable("cityId") String cityId) {
City city = cityService.findCityById(cityId);
return cities;
}
}