通过 JAX-RS 中的 GET 参数映射不同的路由

Map a different route by GET parameter in JAX-RS

在 Spring MVC 中,可以为相同的基本 URI 但使用不同的 GET 参数映射不同的路由(用 @*Mapping 系列注释的方法),例如:

@RestController
@RequestMapping(path = "/test")
public class TestController {

    @GetMapping(params = "myParam=1")
    public void path1() {
        // Called when GET param "myParam" present with value 1
    }

    @GetMapping(params = "myParam=2")
    public void path2() {
        // Called when GET param "myParam" present with value 2
    }

    // Works fine!
}

我尝试使用 JAX-RS 实现相同的路由,但我找不到内置方法。

@Path("/test")
public class TestController {

    @GET
    public void path1() {
        // Should be called when GET param "myParam" present with value 1
    }

    @GET
    public void path2() {
        // Should be called when GET param "myParam" present with value 2
    }

    // What is the missing piece?
}

您使用 QueryParam:

@QueryParam("param1") int param1

例如:

    @GET
    @Path("/test")
    public Response getResponse(
        @QueryParam("param1") int param1,

您还可以在 @Path

中使用正则表达式

@Path("/users/{id: [0-9]*}")

JAX-RS 没有您要查找的映射类型 - 无法根据查询参数进行匹配。通常,该模式是基于路径的。因此,在您的示例中,JAX-RS 的想法更像是:

@Path("/test")
public class TestController {

    @GET
    @Path("/myParam/1")
    public void path1() {
        // will be called when the url ends in /test/myParam/1
    }

    @GET
    @Path("/myParam/2")
    public void path2() {
        // will be called when the url ends in /test/myParam/2
    }
}

但是,话虽如此并扩展@ACV 的回答,您也可以执行以下操作:

@Path("/test")
public class TestController {

    @GET
    public Response routeRequest(@QueryParam("myParam") int myParam) {
        if( myParam == 1 )
            path1();
        else if( myParam == 2 )
            path2();
       // handle bad myParam

      return Response.status(Response.Status.OK).build();
    }

    private void path1() {
        // will be called when GET query param "myParam" present with value 1
    }

    private void path2() {
        // will be called when GET query param "myParam" present with value 2
    }
}

或与上述非常相似的基于路径的示例:

@Path("/test")
public class TestController {

    @GET
    @Path("/myParam/{id}")
    public Response routeRequest(@PathParam("id") int myParam) {
        if( myParam == 1 )
            path1();
        else if( myParam == 2 )
            path2();
       // handle bad myParam

      return Response.status(Response.Status.OK).build();
    }

    private void path1() {
        // will be called when GET path param "myParam" present with value 1
    }

    private void path2() {
        // will be called when GET path param "myParam" present with value 2
    }
}