我正在学习 Spring Boot,并且我有以下代码:
@GetMapping(value = "test/produits/{prixLimit}")
public List<Product> testeDeRequetes(@PathVariable int prixLimit) {
return productDao.findByPrixGreaterThan(400);
}
@GetMapping(value = "test/produits/{recherche}")
public List<Product> testeDeRequetes(@PathVariable String recherche) {
return productDao.findByNameLike("%"+recherche+"%");
}
第一种方法是使用过滤器进行搜索。
第二个是不带过滤器的搜索。
最后我遇到了这个错误:
Ambiguous handler methods mapped for '/test/produits/300': {public java.util.List com.ecommerce.microcommerce.web.controller.ProductController.testeDeRequetes(int), public java.util.List com.ecommerce.microcommerce.web.controller.ProductController.testeDeRequetes(java.lang.String)}
最佳答案
我认为从根本上来说你的 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”。
关于java - 如何正确映射模糊处理程序方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59396387/