java - Spring Web MVC : Regex in controller mapping

标签 java regex spring-mvc

我想升级我的网站 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/

相关文章:

java - 带有spring的jsp中不显示图像

java - 具有 Hibernate/Spring Boot 字段集合的 Spring DTO 的单元测试

javascript - React Router 如何匹配模糊路径和静态路径

Ruby - 匹配字符串中的所有模式

javascript - 将 <li> 行内的文本转换为搜索链接的脚本

spring-mvc - 如何测试 Spring HandlerInterceptor 映射

java - 使用 Java 中的 onClickListener 继续循环迭代

java,从多个图像合成图像

java - 在 struts2 中,是否可以将可选的 patternMapping 与变量一起使用?

java - Spring Security Oauth2 与 JWT 真的是无状态的吗?