javajsonweb-servicesstring-lengthannotated-pojos

Restrict input length using annotation in java POJO


I have a POJO class like below,

    @XmlRootElement
    public class JsonReply {

@XmlElement(nillable = false)
String callResult;

@XmlElement(nillable=false)
String returnobj;

@NotNull
String callError;

public String getCallResult() {
    return callResult;
}

public void setCallResult(String callResult) {
    this.callResult = callResult;
}

public String getCallError() {
    return callError;
}

public void setCallError(String callError) {
    this.callError = callError;
}

To avoid a null string I am using many annotations like Lombok's @NotNull and javax.xml.bind.annotation.XmlRootElement's @XmlElement(nillable=false). And my question is that Is any other way or annotation to restrict a length for Integer or String like min=5 and max=10.

       @Size(max=10)
       @Max(5)
       Integer sampleint;

I am using Jackson. if any annotation is there in Jackson itself like @JsonIgnoreProperties then very fine.

Thanks!


Solution

  • Bean Validation

    You could consider Bean Validation. It's annotations based and integrates with wide variety of frameworks. The reference implementation is Hibernate Validator.

    Here are some highlights that may be useful for you:

    For more details, check the javax.validation.constraints package.

    Bean Validation and Jersey 2.x

    Bean Validation support in Jersey 2.x is provided as an extension module and needs to be mentioned explicitly in your pom.xml file (in case of using Maven):

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-bean-validation</artifactId>
        <version>2.23.2</version>
    </dependency>
    

    If you're not using Maven make sure to have also all the transitive dependencies (see the jersey-bean-validation artifact) on the classpath. This module depends directly on Hibernate Validator which provides a most commonly used implementation of the Bean Validation specification.

    In Jersey, the Bean Validation module is an auto-discoverable features, that is, it's one of the modules where you don't need to explicitly register it's Features (ValidationFeature) on the server as it's features are automatically discovered and registered when you add the jersey-bean-validation module to your classpath.

    For more details, check the Jersey documentation about Bean Validation support.