简体   繁体   中英

Match empty path parameters in REST

I have a service in rest that looks like:

@GET
@Path("get-policy/{policyNumber}/{endorsement}/{type}")
@Produces(MediaType.APPLICATION_XML)
public String getPolicyIndividual(
        @PathParam("policyNumber")String policyNumber,
        @PathParam("endorsement")String endorsement,
        @PathParam("type")String type){
          ...
        }

And i want to know if there is a way that i can accept every parameter as null value if they are not sent, so if somene makes a call to my service without the params or with not all the params still can match the definition of my service. Examples:

http://localhost:8080/service/policy/get-policy/

or this:

http://localhost:8080/service/policy/get-policy/5568

or this:

http://localhost:8080/service/policy/get-policy/5568/4

Im well aware that i can define a regex expression like in this answer , but in that case there was only 1 path param defined, what if i have more than one?

That didnt work for me but maybe im doing something wrong, i tried this with no success:

@GET
@Path("get-policy/{policyNumber: .*}/{endorsement: .*}/{type: .*}")
@Produces(MediaType.APPLICATION_XML)
public String getPolicyIndividual(
        @PathParam("policyNumber")String policyNumber,
        @PathParam("endorsement")String endorsement,
        @PathParam("type")String type){
          ...
        }

is the only way to achive this trough a POST? Im using Jersey btw!

You have to create a complete use case scenario for this and call a general method every time if you dont want to write code multiple times. Say: For an instance use only one parameter passed, then 2 and then all, and none

      @GET
      @Path("get-policy/{policyNumber: .*}")
      @Produces(MediaType.APPLICATION_XML)
      public String getPolicyIndividual(
        @PathParam("policyNumber")String policyNumber)
        {
          doSomething(policyNumber, "", "");
        }

    @GET
    @Path("get-policy/{policyNumber: .*}/{endorsement: .*}")
    @Produces(MediaType.APPLICATION_XML)
    public String getPolicyIndividual(
            @PathParam("policyNumber")String policyNumber, 
            @PathParam("endorsement")String endorsement)
            {
              doSomething(policyNumber,endorsement, "");
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM