javajerseyjava-ws

Java: PUT request without id getting submitted as POST


I have create and update api calls for same entities. If user send a PUT request with no object id, controller accepts it as a POST request and creates a new object.
How can I prevent that?

@POST
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_XML})
public Response create(Entity entity){}


@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_XML })
public Response update(@PathParam("id") int id,Entity entity){}

Is there a way to make request parameter required for update? That may resolve the issue as well.


Solution

  • Add a RegEx pattern from your @Path.

    Syntax:

        @Path("/{" variable-name [ ":" regular-expression ] "}")
    

    Example:

        @Path("/{id: <replace_with_reg_exp>}")