使用多个通配符请求映射

时间:2016-10-06 14:52:53

标签: java spring spring-boot request-mapping

我希望在@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>

2 个答案:

答案 0 :(得分:0)

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

对我来说,作品http://localhost:8080/versions/1会返回version 1

对于没有version/{versionId}的任何其他请求,它会返回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";
    }
}

答案 1 :(得分:0)

如果您想要非常复杂的请求映射,请尝试覆盖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")

现在所有&#34; ... / versions / {versionId}&#34;应转发给&#34; / response_for_versions / {versionId}&#34;所有其他人将由&#34; / **&#34;

处理