具有分层值的Spring RequestMapping URL

时间:2014-06-25 01:07:01

标签: java spring

假设我有一个Category域模型对象,它遵循文件树结构。我希望能够为控制器方法构造一个RequestMapping注释,以便

/category/art/macros
/category/people/weddings/2014/5-19
/category/sports/college/baseball/2014/5-19

可以通过最少数量的控制器方法来处理。

我已经定义了一个控制器方法:

@RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, @PathVariable(value = "category") String category){
    model.addAttribute("message", category);
    return "gallery";
}

这适用于像

这样的单个网址
/category/sports

我如何才能使其更灵活?

1 个答案:

答案 0 :(得分:0)

这里面临的挑战是,您不能使@PathVariable可选,但您可以使用两个或更多可以调用相同服务代码的控制器方法。因此,对于三种URL模式,您必须定义三个不同的控制器:

GET: /category/art/macros

@RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, @PathVariable(value = "category") String category){
    model.addAttribute("message", category);
    return "gallery";
}


GET: /category/people/weddings/2014/5-19

@RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, @PathVariable(value = "category") String category,
    @PathVariable(value = "subcategory") String subcategory,
    @PathVariable(value = "year") String year,
    @PathVariable(value = "date") String date

){
    model.addAttribute("message", category, subcategory, year, date);
    return "gallery";
}

GET: /category/sports/college/baseball/2014/5-19

@RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, @PathVariable(value = "category") String category,
    @PathVariable(value = "subcategory") String subcategory,
    @PathVariable(value = "sub_sub_category") String sub_sub_category,
    @PathVariable(value = "year") String year,
    @PathVariable(value = "date") String date

){
    model.addAttribute("message", category, subcategory, sub_sub_category, year, date);
    return "gallery";
} 

PS您可以使用@RequestParam,它可以是可选的并减少控制器的数量。