使用多个通配符请求映射

Request Mapping with Multiple Wildcards

我想要在 @RequestMapping

中有两个具有通配符的端点
@RequestMapping(value="/**", method = { RequestMethod.GET}, produces = "application/json")

@RequestMapping(value="/**/versions/{versionId}", method = { RequestMethod.GET}, produces = "application/json")

当我执行一个应该转到 /**/versions/{versionId} 的请求时,它更喜欢 /** 端点而不是 /**/versions/{versionId} 端点,即使请求应该匹配。

我正在使用:

<parent>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-parent</artifactId>
    <version>Brixton.SR2</version>
</parent>

我认为您只需更改 @RequestMapping 方法的顺序即可。

对我来说作品 http://localhost:8080/versions/1 returns version 1.

对于没有 version/{versionId} 的任何其他请求 returns index.

@Controller
public class DemoController {

    @RequestMapping(value="/**/versions/{versionId}", method = RequestMethod.GET)
    @ResponseBody
    public String version(@PathVariable String versionId){
        return "version " + versionId;
    }

    @RequestMapping(value="/**", method = RequestMethod.GET)
    @ResponseBody
    public String index(){
        return "index";
    }
}

如果您想要非常复杂的请求映射,请尝试覆盖此处的 handleRequest:How to define RequestMapping prioritization 比你还可以:

if (urlPath.contains("/versions")) {
    /* forward to method with @RequestMapping(value="/get/versions/{versionId}")
}

而不是:

@RequestMapping(value="/**/versions/{versionId}", method = { RequestMethod.GET}, produces = "application/json")

使用:

@RequestMapping(value="/response_for_versions/{versionId}", method = { RequestMethod.GET}, produces = "application/json")

现在所有“.../versions/{versionId}”都应该转发到“/response_for_versions/{versionId}”,所有其他的将由“/**”处理。=14= ]