Spring request mapping to a different method for a particular path variable value

蹲街弑〆低调 提交于 2020-01-14 13:03:55

问题


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



来源:https://stackoverflow.com/questions/32821875/spring-request-mapping-to-a-different-method-for-a-particular-path-variable-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!