Spring request mapping to a different method for a

2019-06-24 12:26发布

问题:

@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 "*".

回答1:

See if this works

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


回答2:

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() { }


回答3:

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.