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.
What is missing is a decalration of bean-class to use for saving the request parameters. In Struts 2, this kind of declaration is done inside the action class. We have to implement the method getModel as you can see in this example:
The bean 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 results previously declared in the jfwexamples.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? All we have to do is create a file with the name of the action and suffix -validation.xml. This file must be saved in the same package of the action class. Here is an example:In the previous code we have defined the validation of field test. The validation type is declared in the attribute type of the tag field-validator. If the validation fails, then the message declared in tag message will be shown. You can find more information on validation here.
The input value declared inside the tag action is the resource (can be a jsp page, an html page, a tile definition or another action) will be returned to the user. For printing the validation error message, the jsp page must contain this tag: