简体   繁体   中英

How to validate Boolean fields in Struts2 using annotations?

Given a Boolean field in an action class like so.

@Namespace("/admin_side")
@ResultPath("/WEB-INF/content")
@ParentPackage(value="struts-default")
public final class TestAction extends ActionSupport implements Serializable, ValidationAware, ModelDriven<Entity>
{
    private Boolean boolField;

    public Boolean getBoolField()
    {
        return boolField;
    }

    public Boolean setBoolField(Boolean boolField)
    {
        this.boolField=boolField;
    }

    @Validations(requiredFields={@RequiredFieldValidator(fieldName="boolField", type= ValidatorType.FIELD, key="delete.row.confirm")})
    @Action(value = "testAction",
            results = {
                @Result(name=ActionSupport.SUCCESS, type="redirectAction", location="Test.action"),
                @Result(name = ActionSupport.INPUT, location = "Test.jsp")},
    public String testAction()
    {            
        return ActionSupport.SUCCESS;
    }

    // The rest of the action class.
}

The field in the action class boolField should be validated only when it is set to true . It may be a hidden field <s:hidden> or it may be set via a query-string parameter.

This and this questions use XML configurations for boolean field validation but do not say anything about annotations.

How to validate such boolean fields using annotations?

I have avoided interceptors and other things to make the code shorten.

You can do this using @FieldExpressionValidator . For example

@Validations(fieldExpressions = @FieldExpressionValidator(fieldName="boolField", expression="boolField == true", message="boolField should be set"))

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