考虑这样一种情况:我们可以有多个具有相同正则表达式的映射,这些映射应该以编程方式进行验证(例如针对数据库(。
(这不是一段有效的代码,我只是想解释我想要实现的目标。请注意网址路径中的正则表达式(
// Animal controller
@GetMapping(path = "/{animal-category [a-z-]+}/{animal-name [a-z-]+}")
public void show(@PathVariable String animalCategory, @PathVariable String animalName) {
// if animalCategory is not found in database, continue with next controller
}
// Plants controller
@GetMapping(path = "/{plant-category [a-z-]+}/{plant-name [a-z-]+}")
public void show(@PathVariable String plantCategory, @PathVariable String plantName) {
// if plantCateogry is not found in database, continue with next controller - as there is no more, it should return 404
}
您可以使用如下所示的常规控制器方法解决此问题:
// General controller method
@GetMapping(path = "/{category [a-z-]+}/{name [a-z-]+}")
public void show(@PathVariable String category, @PathVariable String name) {
// look in database for the category
if(isAnimalCatagory) {
return showAnimal(category, name);
}
else if(isPlantCategory) }
return showPlant(category, name);
}
return "redirect:/404";
}
public void showAnimal(String animalCategory, String animalName) {
// for animal categories
}
public void showPlant(String plantCategory, String plantName) {
// for plant categories
}