【问题标题】:Spring request mapping to a different method for a particular path variable valueSpring请求映射到特定路径变量值的不同方法
【发布时间】:2015-09-28 11:27:51
【问题描述】:
@Controller
@RequestMapping("/authors")
public class AuthorController {
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Author getAuthor(
        final HttpServletRequest request,
        final HttpServletResponse response,
        @PathVariable final String id)
    {
        // Returns a single Author by id
        return null;
    }

    @RequestMapping(value = "/{id}/author-properties", method = RequestMethod.GET)
    public AuthorProperties getAuthorProperties(
        final HttpServletRequest request,
        final HttpServletResponse response,
        @PathVariable final String id)
    {
        // Returns a single Author's List of properties
        return null;
    }

    @RequestMapping // How to map /authors/*/author-properties to this method ????
    public List<AuthorProperties> listAuthorProperties(
        final HttpServletRequest request,
        final HttpServletResponse response)
    {
        // Returns a single Author's List of properties
        return null;
    }
}

class Author {
    String propertiesUri;
    // other fields
}

class AuthorProperties {
    String authorUri;
    // other fields
}

基本上我需要:

  • /authors - 列出所有作者
  • /authors/123 - 通过 id 123 获取作者
  • /authors/123/author-properties - 获取 123 作者的 AuthorProperties 对象
  • /authors/*/author-properties - 获取所有作者的 AuthorProperties 列表

当我尝试时

@RequestMapping(value = "/*/author-properties", method = RequestMethod.GET)

它仍在将/authors/*/author-properties 映射到getAuthorProperties 方法,路径变量值为“*”。

【问题讨论】:

  • 当我将 /*/author-properties 的方法保留在 /{id}/author-properties 的方法之前,它就开始工作了。那么这是一个适当的解决方案吗?我们是否可以始终将映射的处理顺序作为方法声明的顺序进行传递?

标签: java spring spring-mvc controller


【解决方案1】:

看看这是否有效

@RequestMapping(value = "/{id:.*}/author-properties", method = RequestMethod.GET)

【讨论】:

    【解决方案2】:

    您可以使用正则表达式限制单个作者的映射,例如:

    @RequestMapping("/{authorId:\\d+}/author-properties")
    public String authorProperties(@PathVariable String authorId) {}
    

    这只会匹配作者 ID 为数字的 URL。

    对于您可以使用的所有作者属性的请求:

    @RequestMapping("/*/author-properties")
    public String allProperties() { }
    

    Hovewer * 具有特殊含义,因此它也将匹配 /foo/author-properties。要解决它,您可以使用以下内容:

    @RequestMapping("/{all:\\*}/author-properties")
    public String allProperties() { }
    

    【讨论】:

      【解决方案3】:

      如果为所有作者获取 AuthorProperties 列表是常见的情况,那么我认为您应该创建一个这样的 URI:“/author-properties”。否则 Bohuslav 给出的答案就是你想要的。

      【讨论】:

        猜你喜欢
        • 2012-04-21
        • 1970-01-01
        • 2023-04-04
        • 2011-02-14
        • 2019-05-12
        • 1970-01-01
        • 2015-04-11
        • 1970-01-01
        • 2017-04-18
        相关资源
        最近更新 更多