在一个spring启动控制器类中公开了2个api。我有一个要求,只拦截一个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;
}
}
在你的拦截器中,你可以检查你想要拦截的端点的请求URI。
您可以使用正则表达式来匹配URI。以下为/cities/{cityId}
端点
if (request.getRequestURI().matches("(\/cities\/[a-zA-Z0-9]+\/?)")) {
validateHeaderParam(request);
request.setAttribute("startTime", startTime);
}
我不确定在你的拦截器中想要做什么,但对于你的例子,你也可以在你的控制器中这样做。像这样,
@GetMapping(value = "/cities/{cityId}")
public City getCityById(@PathVariable("cityId") String cityId, HttpServletRequest request) {
// Here you can use HttpServletRequest and do your validation
// validateHeaderParam(request);
// request.setAttribute("startTime", startTime);
City city = cityService.findCityById(cityId);
return cities;
}
更简洁的方法是使用基于java的配置。点击这里阅读更多内容
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
}
}