在Spring REST控制器中,是否可以有一个基于请求参数值的处理程序方法?
例如,我希望仅在type
参数的值为product时才调用处理程序方法。
http://localhost:8080/api/vi/catalog?type=product
答案 0 :(得分:1)
Spring仅根据路径和查询参数匹配请求。
我认为您应该尝试其他方法,例如:/api/v1/catalog/product
在这种情况下更合理。
答案 1 :(得分:0)
我认为最好的方法是将HandlerInterceptor绑定到路径“ / api / vi / catalog”。 这是一个示例,如果参数未设置为product,则Interceptor返回404响应:
@Component
public class ProductInterceptorHandler implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!request.getParameter("type").equalsIgnoreCase("product")){
response.setStatus(404);
// DO WHATEVER YOU WANT TO INFORM USER THAT IS INVALID
return false;
}
return true;
}
}
您应该将其绑定到配置类内部的路径(在我的示例中是扩展WebMvcConfigurerAdapter的SpringBootApplication):
@SpringBootApplication
public class ASpringApplication extends WebMvcConfigurerAdapter implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ASpringApplication.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new ProductInterceptorHandler()).addPathPatterns("/api/vi/catalog");
}
}
最后是restcontroller方法:
@RequestMapping(value = "/api/vi/catalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> searchLocationIndexed(@RequestParam("type") String type ) throws Exception {
return ResponseEntity.ok("ok");
}