简体   繁体   中英

Bean Validation using JAX-RS and DTO parameters

I'm trying to use Bean Validations on my JAX-RS services. But I can't make it work with validations using a JSON object instead of simple parameters.

I have this REST interface:

@Path("persons")
@Produces(MediaType.APPLICATION_JSON)
public class PersonRestService {

    @EJB
    private GreeterEJBLocal greeterEJB;

    @POST
    @Path("greet")
    @Consumes(MediaType.APPLICATION_JSON)
    public SayHelloRestResponse sayHello(SayHelloRestRequest sayHelloRestRequest) {
        SayHelloRestResponse sayHelloRestResponse = new SayHelloRestResponse();
        Person person = new Person();
        person.setName(sayHelloRestRequest.person.name);
        person.setEmail(sayHelloRestRequest.person.email);

        SayHelloRequest sayHelloRequest = new SayHelloRequest();
        sayHelloRequest.setPerson(person);

        SayHelloResponse sayHelloResponse = greeterEJB.sayHello(sayHelloRestRequest.person.name, sayHelloRestRequest.person.email);

        sayHelloRestResponse.setMessage(sayHelloResponse.getMessage());

        return sayHelloRestResponse;
    }
}

And this is my DTO with Bean Validation annotations:

public class SayHelloRestRequest implements Serializable {

    // Default serial version UID
    private static final long serialVersionUID = 1L;

    public Person person;

    public static class Person {
        @Size(min = 2, max = 5, message = "{person.name.size}")
        public String name;
        @Email(message = "{person.email.email}")
        public String email;
    }

}

When I'm testing the service never fail for the validation. I don't know I'm doing wrong. There is a screenshot were I'm testing the service

在此处输入图片说明

You need to add @Valid to your method signature:

SayHelloRestResponse sayHello(@Valid SayHelloRestRequest sayHelloRestRequest) {

The @Valid annotation ensures that your DTO is validated at runtime.

If you're using RESTEasy, you'd need to annotate your method(or class) with @ValidateRequest which comes from:

<dependency>
   <groupId>org.jboss.resteasy</groupId>
   <artifactId>resteasy-hibernatevalidator-provider</artifactId>
   <version>2.3.1.GA</version>
</dependency>

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