Validating Nested Parameters Using XDoclet
For some time, users of Struts and XDoclet have been able to generate the validation.xml file used by the Commons Validator to validate client input. Using the validator XDoclet tags is pretty simple: just place the relevant tags on the setter methods of your POJOs and run the appropriate Ant task. Here’s an example using DynaForms:
* @struts.dynaform name=”personForm”
* type=”org.apache.struts.validator.DynaValidatorActionForm”
* validate=”true”
*/
public class Person {
private Long id;
private String name;
private String notes;
public void setId(Long id) { this.id = id; }
public Long getId() { return this.id; }
/**
* @struts.validator type=”required”
* @struts.validator-args arg0resource=”person.name”
*/
public void setName(String name) { this.name = name; }
public String getName() { return this.name; }
/**
* @struts.validator type=”maxlength”
* @struts.validator-args arg0resource=”person.notes”
* @struts.validator-args arg1value=”${var:maxlength}”
* @struts.validator-var name=”maxlength” value=”4000″
*/
public void setNotes(String notes) { this.notes = notes; }
public String getNotes() { return this.notes; }
}
The problem that many people seem to be having is validating nested objects. Suppose our Person class has an Address property that we also need to validate. To do this, we first need to add the appropriate struts.validator tags to the Address class:
private String line1;
private String line2;
/**
* @struts.validator type=”required”
* @struts.validator-args arg0resource=”address.line1″
*/
public void setLine1(String line1) { this.line1 = line1; }
public String getLine1() { return this.line1; }
/**
* @struts.validator type=”required”
* @struts.validator-args arg0resource=”address.line2″
*/
public void setLine2(String line2) { this.line2 = line2; }
public String getLine2() { return this.line2; }
}
With that done, we just need to add the struts.validator tags to the Address setter in the Person class:
* @struts.validator
*/
public void setAddress(Address address) { this.address = address; }
The nested properties will now be validated as you expect.
Uncategorized