我认为基本上你的 API 是模棱两可的。作为消费者,相同的动词 + 路径会让我感到困惑。
这也有点限制。例如,通过您的设置,您将阻止用户搜索“123”(可能是产品 ID 或 SKU)。
prixLimit 和 recherche 参数似乎是产品资源上的过滤器/查询,因此将它们作为查询参数而不是路径传递更有意义:
@GetMapping(value = "test/produits/")
public List<Product> testeDeRequetes(@RequestParam(name = "prixLimit", required = false) Integer prixLimit,
@RequestParam(name = "recherche", required = false) String recherche {
// if prixLimit is not null
// return productDao.findByPrixGreaterThan(prixLimit);
// else if recherche is not null
// return productDao.findByNameLike("%"+recherche+"%");
// else
// return some meaningful default behavior such as all
// products, or return 400 to indicate a bad request
}
但如果使用路径是此 API 的必需部分,则有几个选项可以消除歧义:
添加额外的路径元素
@GetMapping(value = "test/produits/prixLimit/{prixLimit}")
public List<Product> testeDeRequetes(@PathVariable int prixLimit) {
return productDao.findByPrixGreaterThan(prixLimit);
}
@GetMapping(value = "test/produits/recherche/{recherche}")
public List<Product> testeDeRequetes(@PathVariable String recherche) {
return productDao.findByNameLike("%"+recherche+"%");
}
使用单一方法处理两者
@GetMapping(value = "test/produits/{param}")
public List<Product> testeDeRequetes(@PathVariable String param) {
// if param is an int...
// return productDao.findByPrixGreaterThan(param);
// else
// return productDao.findByNameLike("%"+param+"%");
}
在路径映射中使用正则表达式
这仍然有点限制,因为两个正则表达式模式必须是互斥的,否则您将得到相同的重复映射异常:
// This can only handle digits
@GetMapping(value = "test/produits/{prixLimit:[0-9]+}")
public List<Product> testeDeRequetes(@PathVariable int prixLimit) {
return productDao.findByPrixGreaterThan(400);
}
// This can only handle characters
@GetMapping(value = "test/produits/{recherche:[A-Za-z]+}")
public List<Product> testeDeRequetes(@PathVariable String recherche) {
return productDao.findByNameLike("%"+recherche+"%");
}
请注意,在这种情况下您不能搜索“abc123”。