0

我在Spring PetClinic 示例应用程序的 OwnerController 类中添加了以下方法:

//'''''''''CodeMed added this next method
@RequestMapping(value = "/owners/catowners", method = RequestMethod.GET)
public String findOwnersOfPetType(Map<String, Object> model) {
    // find owners of a specific type of pet
    Integer typeID = 1;//this is just a placeholder
    Collection<Owner> results = this.clinicService.findOwnerByPetType(typeID);
    model.put("selections", results);
    return "owners/catowners";
 }
//'''''''''''''''''''

由于 petclinic 数据库中猫的 typeID 为 1,因此上面返回了猫主人的列表。但我也想在网站上为狗主人、蜥蜴主人、仓鼠主人和任何其他宠物的主人创建单独的页面。我需要为每种宠物类型创建一个单独版本的 findOwnersOfPetType() 吗?像 findDogOwners()、findLizardOwners()、findHamsterOwners() 等?或者我可以让 findOwnersOfPetType() 方法接受一个指示宠物类型的 int 参数吗?

jsp文件呢?我需要为 catowners.jsp、dogowners.jsp、lizardowners.jsp、hamsterowners.jsp 等每个文件创建一个单独的 jsp 文件吗?或者我可以以某种方式创建一个jsp,为每种类型的宠物填充相同格式的不同数据?

这在代码中看起来如何?

ClinicService 和 OwnerRepository 函数已经一起处理了,因为我上面发布的函数使用函数中创建的参数调用了 ClinicService 方法。

4

2 回答 2

1

您可以将 aRequestMapping与 a 一起使用PathVariable。例如:

@RequestMapping(value = "/owners/{petId}", method = RequestMethod.GET)
public String findOwnersOfPetType(Map<String, Object> model,
    @PathVariable int petId) {
    //use id as before
}

如果您想在 URL 中使用字符串而不是整数,则可以通过在 URL 中使用字符串并在这些字符串及其 ID 之间进行枚举映射来使它们更加用户友好。

于 2013-09-06T19:49:17.207 回答
1

您可以在请求映射中添加类型参数:

@RequestMapping(value = "/owners/{type}", method = RequestMethod.GET)
public String findOwnersOfPetType(@PathVariable("type") it type) {

}

所以你不需要不同的控制器方法来处理多种类型。

服务方法取决于您如何为域对象建模。如果您有一个Pet包含 a 的类,petType您可以轻松地执行以下操作:

Collection<Owner> results = this.clinicService.findOwnerByPetType(type);

然后服务调用repository 方法,该方法findOwnerByPetType(type)返回所有者列表

于 2013-09-06T19:52:00.943 回答