有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用多个通配符的java请求映射

我想要两个端点在@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) 个答案

  1. # 1 楼答案

    如果您想要相当复杂的请求映射,请尝试覆盖HandlerRequest,因为它在这里: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}”,其他所有的都将由“/**”处理

  2. # 2 楼答案

    我认为你只需要改变@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";
        }
    }