バシルAmazigh Badjadj:
私は春のブートについて学んだし、私はこのコードを持っています:
@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+"%");
}
パスマッピングで正規表現を使用します
2つの正規表現パターンは相互に排他的でなければならないので、これはまだ少し制限しているか、同じ重複マッピング例外を取得します:
// 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」を検索することはできません。