Struts 2 Tutorial – Validation and Error Handling

09/20/2008

Validation is an important part of any web framework because it is one of the most painfully repetitive things to have to continually recreate.  In Struts 2, validation is handled by creating an Action-validation.xml file.  So, if we have an AddUser Action then we would create an AddUser-validation.xml file:

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
  <field name="userId">
    <field-validator type="requiredstring">
      <message>Username is required</message>
    </field-validator>
  </field>
</validators>

It is important that you have both a getter and setter for the field you are validating.  For example, AddUser would need both of the following method signatures for validation to work properly: “public String getUserId()” and “public void setUserId(String userId)”.  You can get more information about the other types of validators from the Struts 2 documentation.

You can also control error handling from your Action class.  For example, let’s say that the user picks a username which is already registered.  We wouldn’t be able to determine this with validation alone, but would need to check the database in our Action class.  So when we determine that we can call “addActionError(String message)” from our class.  Then when we want to print any errors out on our page, we simply use the tag:

<s:actionerror />
Be Sociable, Share!