Spring request mapping to a different method for a

2019-06-24 12:04发布

@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
}

Basically I need:

  • /authors - listing all the authors
  • /authors/123 - fetching author by id 123
  • /authors/123/author-properties - fetching the AuthorProperties object for a 123 author
  • /authors/*/author-properties - fetching List of AuthorProperties for all authors

When I tried

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

It was still mapping /authors/*/author-properties to getAuthorProperties method with path variable value as "*".

3条回答
女痞
2楼-- · 2019-06-24 12:16

If fetching List of AuthorProperties for all authors is common case, then I think that you should make an URI like this: "/author-properties". Otherwise answer given by Bohuslav is what you want.

查看更多
smile是对你的礼貌
3楼-- · 2019-06-24 12:34

See if this works

@RequestMapping(value = "/{id:.*}/author-properties", method = RequestMethod.GET)
查看更多
萌系小妹纸
4楼-- · 2019-06-24 12:34

You can constraint the mapping for individual author using regular expressions, such as:

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

This will only match URLs where the author ID is numeric.

For the request for all author properties you can use:

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

Hovewer * has special meaning so it will match /foo/author-properties also. To work around it you can use something like:

@RequestMapping("/{all:\\*}/author-properties")
public String allProperties() { }
查看更多
登录 后发表回答