Java 使用Jersey进行意外的REST映射

Java 使用Jersey进行意外的REST映射,java,rest,jersey,jax-rs,Java,Rest,Jersey,Jax Rs,在下面的测试用例#3中,我使用了一种意想不到的方法。是否有更好的映射策略 @Path("/pets") @GET @Path("/{petId}") public Response getPet(@PathParam("petId") String petId){ //fetch a single pet record } @GET @Path("/owner/{ownerId}") //fetch collection of pet records for a

在下面的测试用例#3中,我使用了一种意想不到的方法。是否有更好的映射策略

@Path("/pets")


@GET
@Path("/{petId}")       
public Response getPet(@PathParam("petId") String petId){ 
    //fetch a single pet record
}

@GET
@Path("/owner/{ownerId}")   //fetch collection of pet records for an owner
public Response getPetListByOwner(@PathParam("ownerId") String ownerId){ 
    //fetch a list of pet records by ownerId
    //Validate ownerId not null...
}
测试用例#1
/宠物/123
//正确调用getPet(“123”)

测试用例#2
/宠物/主人/456
//正确调用getPetListByOwner(“456”)

测试用例#3
/宠物/主人

//意外地调用getPet()。Jersey使用“owner”作为getPet()的petId,并调用getPet(“owner”)。我希望代码调用getPetListByOwner(),在这里我可以进行null检查并返回一个需要ownerId的响应,但是我使用了错误的方法(getPet())。虽然我不希望人们点击这个网址,但我无法阻止他们。我也不想搜索一只用petId=“owner”执行的宠物

有更好的映射策略吗?

定义另一个显式映射到路径
/owner
(没有其他路径参数)的端点方法,并从中返回错误响应

@Path("/pets")


@GET
@Path("/{petId}")       
public Response getPet(@PathParam("petId") String petId){ 
    //fetch a single pet record
}

@GET
@Path("/owner/{ownerId}")   //fetch collection of pet records for an owner
public Response getPetListByOwner(@PathParam("ownerId") String ownerId){ 
    //fetch a list of pet records by ownerId
    //Validate ownerId not null...
}
@GET
@Path("/owner")
public Response getPetListByOwner() {
    return Response
            .status(Response.Status.BAD_REQUEST)
            .build();
}
或者,您可以只使用一个端点方法和一些与路径模板匹配的正则表达式来实现它,以声明
/owner
之后的部分是可选的。本教程提供了有关在
@PathParam
模板中使用正则表达式的信息


我更喜欢显式声明额外端点方法的可读性,但这有点主观。

定义另一个显式映射到路径
/owner
(没有其他路径参数)的端点方法,并从那里返回错误响应

@GET
@Path("/owner")
public Response getPetListByOwner() {
    return Response
            .status(Response.Status.BAD_REQUEST)
            .build();
}
或者,您可以只使用一个端点方法和一些与路径模板匹配的正则表达式来实现它,以声明
/owner
之后的部分是可选的。本教程提供了有关在
@PathParam
模板中使用正则表达式的信息


我更喜欢显式声明额外端点方法的可读性,但这有点主观。

这是因为您将路径参数声明为字符串。相反,将其声明为int

代码应该如下所示

@Path("/pets")


@GET
@Path("/{petId}")       
public Response getPet(@PathParam("petId") int petId){ 
    //fetch a single pet record
}

@GET
@Path("/owner/{ownerId}")   //fetch collection of pet records for an owner
public Response getPetListByOwner(@PathParam("ownerId") int ownerId){ 
    //fetch a list of pet records by ownerId
    //Validate ownerId not null...
}

这样您就不会遇到将
顺序
识别为ID的问题

这是因为您将路径参数声明为字符串。相反,将其声明为int

代码应该如下所示

@Path("/pets")


@GET
@Path("/{petId}")       
public Response getPet(@PathParam("petId") int petId){ 
    //fetch a single pet record
}

@GET
@Path("/owner/{ownerId}")   //fetch collection of pet records for an owner
public Response getPetListByOwner(@PathParam("ownerId") int ownerId){ 
    //fetch a list of pet records by ownerId
    //Validate ownerId not null...
}
这样您就不会遇到将
订单
识别为ID的问题