简体   繁体   中英

How to validate an empty Collection in Struts2?

In an action class, I have a List something like the following.

private List<SomeEntity>entity=new ArrayList<SomeEntity>();

public List<SomeEntity> getEntity()
{
    this.entity=someService.getList();  //Initialize after some ugly conditional checks, lazy loading.
    return this.entity;
}

//Setter is not required in this case.

I need to initialize it at the declaration place for some reason.


Since this List is not null (and in fact, it can never be null , in this case), in an action method, a validator like the following,

@Validations(
        requiredFields={
            @RequiredFieldValidator(fieldName="entity", type=ValidatorType.FIELD, key="key.required")})
public String doAction()
{
    return ActionSupport.SUCCESS;
}

will not work (I expect a validation error to occur here, since the list does not contain any object(s), its size is zero).

So, how to validate this field entity , if its size zero?

I use Struts 2.3.16.

You can use fieldexpression validator for that.

XML validation:

<field name="subscripcion">
    <field-validator type="fieldexpression">
        <param name="expression"><![CDATA[entity.size != 0]]></param>
        <message>...</message>
    </field-validator>
</field>

Or annotation:

@FieldExpressionValidator(expression = "entity.size != 0")

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