JAVA How to JAVA Development tutorials and how to

25Jun/100

How to validate through annotations: Struts 2

Struts 2 validation - JAVA How to

Hi to all. I've studied some stuff about struts 2 those days so i've learn a lot of new things like this post topic. Normally, what do you do when you want to implement a basic validation on Struts 2? The steps about how to do that are:

  • Assure that you're using defaultStack interceptor stack because inside it are workflow and validation interceptors that are responsible of execute validation logic and redirect to appropiate result when validation triggers.
  • Define a result named "input" in action's declaration on struts.xml . This is the result where validation must redirect automatically if exists validation errors. If input result is not defined it will give an error of result not found.
  • Override validate() method on your action.
  • Write your own validation logic inside it, that must add error messages when it fails to properly validation mechanism. For example, if i validate that a field must be a number and greater than 1000, if it doesn't pass the validation it must add a error message using addActionError() or addFieldError() (To follow standards you should use addFieldError() ), like this:
    if (fieldOne == null || fieldOne.equals("")) {
     addFieldError("fieldOne", "Field one must not be empty.");
     }
     if (fieldTwo == null || Integer.valueOf(fieldTwo) < 30) {
     addFieldError("fieldTwo", "Field two must be greater or equal than 30.");
     }
  • (Optional) in your jsp you can define <s:fielderror> or <s:actionerror> tags to print your validation messages. As you can guess, <s:fielderror> prints validation errors added with addFieldError() and <s:actionerror> to print action error messages added with addActionError(). To print validation errors from fieldOne and fieldTwo you have to define <s:fielderror> like this:
    <s:fielderror cssClass="cssClassForUllistwithLi" >
     <s:param>fieldOne</s:param>
     <s:param>fieldTwo</s:param>
     </s:fielderror>
  • Run your app :P

This is the basic way. But if you want to validate through annotations is easier and faster, you have to do this: