In the other section, we have learned how to use a simple action, now it is time to learn how to use an action in combination with a form that returns data that must be validated. For this purpose we will create a simple application that checks the number of digits in a number. For this we need an action:
As we can see in the text area above, the declaration of the
action is a little different, more precisely there are more
attributes in the action element.
Let's focus on name, its value has to match with the value of the name attribute of another element present in the struts-config.xml file. The element is the form-bean and it maps this logical name to the actual bean class associated to the form.
In this way, the framework will take care of creating a bean of type HomeActionForm and when the form is submitted, load the data from the form into the bean and pass it to the action class. Here follows the HomeActionForm class.
The bean extends the class ProjectActionForm and has a member String named test. The action class will retrieve the string from the bean and based on its content, will choose one of the two forwarding paths previously declared in the struts-config.xml file.
The code above shows us how to retrieve the bean containing the data of the form.
But how and when does the validation occur? Let's take a look again at the action declaration, and precisely at the attributes input, scope and validation.
The input value is the resource from which the control is passed to the action, so if the validation fails, the control will return to the resource that passed it (JSP page, action etc...). The validate attribute is quite self explanatory and the scope attribute tells us the scope of the bean, it can be a request or a session. The validation rules are stored in another configuration file validation.xml.
We can notice that the element form has an attribute name with value
home_form, the logical name of the bean. The field element has a
property attribute that matches the property of the form bean. In this way, the
framework can retrieve its value and check it against the rules defined by the
other attributes. The depends attribute can contain many pre-defined validation
rules, in this case required and maxlength. The required rule is quite self
explanatory: the field is mandatory, the maxlength is also easily understandable
but this time we need to define the maximum length of the string. So we need a
variable, associate it with the maxlegth rule so the validator can perform a
proper check, and this is what the var element does.
If an action needs to make some kind of initialization, for example valorize a class attribute used by all the requests, the myInit method can be used. This method is executed only once by the framework when the instance of the action class is created.