我想升级我的网站 URL 映射。
以前它纯粹是基于查询的,例如:
http://mydomain.com?brand=samsung&category=mobile&min_price=20&max_price=50&offer=10
现在我想将我的 URL 转换为更像 REST。
我希望它看起来像这样:
http://mydomain.com/samsung/mobiles?min_price=20&max_price=50&offer=10
或者采用更具描述性的格式:
http://mydomain.com/brand/samsung/category/mobiles?min_price=20&max_price=50&offer=10
我相信我需要在 spring Controller 的映射中使用正则表达式。 我不太擅长写正则表达式, 但从谷歌获得了一些有用的资源。 我读过这个spring reference document但无法找出正则表达式来解决我的要求。
请给我一个简单的演示或任何问题的解决方案。
最佳答案
我认为您想通过两步方法来解决这个问题。
第 1 步是为每种可能的 URL 格式编写一个处理程序
第 2 步是实现与处理程序分开的实际功能,并从处理程序中调用它。
使用@RequestParam(required=false)
作为可选参数。
// copy from the Lance Java answer.
@RequestMapping(value="/{brand}/{category}/", method=RequestMethod.GET)
public ModelAndView search1(
@PathVariable String brand,
@PathVariable String category,
@RequestParam String minPrice,
@RequestParam String maxPrice,
@RequestParam Integer offer)
{
return actualSearch(brand, category, minPrice, maxPrice, offer);
}
@RequestMapping(value="/{brand}/", method=RequestMethod.GET)
public ModelAndView search1(
@PathVariable String brand,
@RequestParam String minPrice,
@RequestParam String maxPrice,
@RequestParam Integer offer)
{
return actualSearch(brand, null, minPrice, maxPrice, offer);
}
@RequestMapping(value="/brand/{brand}/category/{category}/",
method=RequestMethod.GET)
public ModelAndView search2(
@PathVariable String brand,
@PathVariable String category,
@RequestParam String minPrice,
@RequestParam String maxPrice,
@RequestParam Integer offer)
{
return actualSearch(brand, category, minPrice, maxPrice, offer);
}
@RequestMapping(value="/brand/{brand}/", method=RequestMethod.GET)
public ModelAndView search2(
@PathVariable String brand,
@RequestParam String minPrice,
@RequestParam String maxPrice,
@RequestParam Integer offer)
{
return actualSearch(brand, null, minPrice, maxPrice, offer);
}
private ModelAndView actualSearch(
final String brand,
final String category,
final String minPrice,
final String maxPrice,
final Integer offer)
{
... blah
}
关于java - Spring Web MVC : Regex in controller mapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365967/