Ejaz Ahmed
Ejaz Ahmed

Reputation: 339

RESTful web service post request validation for required fields

In Java RESTful service request parameter validation, an error should be thrown if the required parameters does not exist in the request payload.

I've tried the following but it didn't work:

public class OrderItemDetailsDTO {

    @XmlElement(required = true)
    private long orderItemId;

    // getters and setters...
}

I also tried @NotNull, @min(1), but none of them worked. The URL is called and method executes even if the required parameter is not present and then the method throws an exception which I don't want.

Is there any way so that the error is thrown, saying required element is not present, before going to the method?...

Upvotes: 1

Views: 2149

Answers (1)

mr. Holiday
mr. Holiday

Reputation: 1800

Please take a look at this article. And here is a small code snippet based on that article as well. I hope this helps

public class OrderItemDetailsDTO {

    @XmlElement
    @Min(1)
    private long orderItemId;

    // getters and setters...
 }

@Path("orders")
public class OrdersResource {
  @POST
  @Consumes({ "application/xml" })
  public void place(@Valid OrderItemDetailsDTO order) {
    // Jersey recognizes the @Valid annotation and
    // returns 400 when the JavaBean is not valid
  }
}

Upvotes: 1

Related Questions