Struts Annotation

The struts annotation are explained here. There are different struts2 annotation and they add apt generation support for struts based annotated projects, such as TLD and documentation generation from annotated component classes as used in struts2. Strut annotations mainly classified into four categories.

Action annotations

Action annotations are used when the framework scans the classpath for action classes rather than defining individual mapping through XML configuration. The usage of this annotation is placed at the class level. The commonly used annotations are,

Namespace Annotation: – It overrides the namespace of an action. The @Namespace annotation permits the definition of an Action’s namespace in the Action class rather than based on Zero Configuration’s conventions. The usage of this annotation is placed at the class level.

ParentPackage Annotation: – This annotation defines an existing configuration package for the action’s package to extend. The @ParentPackage annotation permits the definition of Action’s package for an action found through Zero Configuration.

Result Annotation: – It defines an action Result. The @Results annotations to be configured correctly you must set the actionPackages filter init-param to a comma-separated list of packages containing the annotated Action classes.

Eg: –

@
public class HomeAction extends ActionSupport
{
// ...
}
Results Annotation: - It defines multiple Results.
Eg: - @Results( {
@Result(name=“success”, value=“/home.page”, type=TilesResult.class),
@Result(name=“homeError”, value=“/homeError.page”, type=TilesResult.class)
} )
public class HomeAction extends ActionSupport {
// ....
}
Result(name=“success”, value=“/home.page”,.class)

Interceptor annotations

To use interceptor annotations, we have to specify the AnnotationWorkflowInterceptor to your interceptor stack. The After annotation can be applied at method level. The commonly used interceptor annotations are,

After Annotation: – This annotation marks an action method that needs to be executed after the result. Marks an action method that needs to be called after the main action method and the result was executed. Return value is ignored.

Eg: –

 public class SampleAction extends ActionSupport {
@After
public void isValid() throws ValidationException {
// validate model object, throw exception if failed
}
public String execute() {
// perform action
return SUCCESS;
}
}

Before Annotation: – The Before annotation marks an action method that needs to be executed before the main action method. Marks an action method that needs to be executed before the main action method.

Eg: –

public class SampleAction extends ActionSupport {
@Before
public void isAuthorized() throws AuthenticationException {
// authorize request, throw exception if failed
}
public String execute() {
// perform secure action
return SUCCESS;
}
}

BeforeResult Annotation: – This annotation marks an action method that needs to be executed before the result. Marks an action method that needs to be executed before the result. Return value is ignored.

Eg: –

public class SampleAction extends ActionSupport {
@BeforeResult
public void isValid() throws ValidationException {
// validate model object, throw exception if failed
}
public String execute() {
// perform action
return SUCCESS;
}  }

Validation annotations

To use annotation-based validation, annotate the class or interface with Validation Annotation. The validation annotation must be applied at method level. The commonly used validation annotations are,

ConversionErrorFieldValidator Annotation: – It checks if there are any conversion errors for a field. This validator checks if there are any conversion errors for a field and applies them if they exist

Eg: –

@ConversionErrorFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true)
@DateRangeFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, min = “2005/01/01”, max = “2005/12/31”)
@DoubleRangeFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, minInclusive = “0.123”, maxInclusive = “99.987”)
@EmailValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true)

DateRangeFieldValidator Annotation: – This annotation checks that a date field has a value within a specified range.

Eg: –

DoubleRangeFieldValidator Annotation:- It checks that a double field has a value within a specified range.

Eg: –

EmailValidator Annotation: – It checks that a field is a valid e-mail address.

Eg: –

ExpressionValidator Annotation: – It validates an expression.

Eg: –

@ExpressionValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, expression = “an OGNL expression” )
@FieldExpressionValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, expression = “an OGNL expression”)

FieldExpressionValidator Annotation: – It uses OGNL expression to perform its validator.

Eg: –

IntRangeFieldValidator Annotation: – this annotation checks that a numeric field has a value within a specified range.

Eg: – @IntRangeFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, min = “0”, max = “42”)

RegexFieldValidator Annotation: – It validates a regular expression for a field.

Eg: – @RegexFieldValidator( key = “regex.field”, expression = “yourregexp”)

RequiredFieldValidator Annotation: – It checks that a field is non-null.

Eg: – @RequiredFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true)

RequiredStringValidator Annotation: – This annotation checks that a String field is not empty.

Eg: – @RequiredStringValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, trim = true)

StringLengthFieldValidator Annotation: – It checks that a String field is of the right length.

Eg: – @StringLengthFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true, trim = true, minLength = “5”,  maxLength = “12”)

StringRegexValidator Annotation: – It invokes a regular expression to validate a String field.

UrlValidator Annotation: – It checks that a field is a valid URL.

Eg: – @UrlValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true)

Validation Annotation: – It is a marker annotation for validation at Type level.

Eg: –

@Validation()
public interface AnnotationDataAware {
void setBarObj(Bar b);
Bar getBarObj();
@RequiredFieldValidator(message = “You must enter a value for data.”)
@RequiredStringValidator(message = “You must enter a value for data.”)
void setData(String data);
String getData();
}

Validations Annotation: – It used to group validation annotations.

Eg: –

@Validations(
requiredFields =
{@RequiredFieldValidator(type = ValidatorType.SIMPLE,
fieldName = “customfield”, message = “You must enter a value for field.”)},
requiredStrings =
{@RequiredStringValidator(type = ValidatorType.SIMPLE,
fieldName = “stringisrequired”, message = “You must enter a value for string.”)},
emails =
{ @EmailValidator(type = ValidatorType.SIMPLE,
fieldName = “emailaddress”, message = “You must enter a value for email.”)},
urls =
{ @UrlValidator(type = ValidatorType.SIMPLE, fieldName = “hreflocation”, message = “You must enter a value for email.”)},
stringLengthFields =
{@StringLengthFieldValidator(type = ValidatorType.SIMPLE,
trim = true, minLength=“10” , maxLength = “12”, fieldName = “needstringlength”, message = “You must enter a stringlength.”)},
intRangeFields =
{ @IntRangeFieldValidator(type = ValidatorType.SIMPLE,
fieldName = “intfield”, min = “6”, max = “10”, message = “bar must be between ${min} and ${max}, current value is ${bar}.”)},
dateRangeFields =
{@DateRangeFieldValidator(type = ValidatorType.SIMPLE,
fieldName = “datefield”, min = “-1”, max = “99”, message = “bar must be between ${min} and ${max}, current value is ${bar}.”)},
expressions = {
@ExpressionValidator(expression = “foo > 1”, message = “Foo must be greater than Bar 1. Foo = ${foo}, Bar = ${bar}.”),
@ExpressionValidator(expression = “foo > 2”, message = “Foo must be greater than Bar 2. Foo = ${foo}, Bar = ${bar}.”),
@ExpressionValidator(expression = “foo > 3”, message = “Foo must be greater than Bar 3. Foo = ${foo}, Bar = ${bar}.”),
@ExpressionValidator(expression = “foo > 4”, message = “Foo must be greater than Bar 4. Foo = ${foo}, Bar = ${bar}.”),
@ExpressionValidator(expression = “foo > 5”, message = “Foo must be greater than Bar 5. Foo = ${foo}, Bar = ${bar}.”)
}
)
public String execute() throws Exception {
return SUCCESS;
}

VisitorFieldValidator Annotation: – This annotation invokes the validation for a property’s object type.

Eg: –

@VisitorFieldValidator(message = “Default message”, key = “i18n.key”, shortCircuit = true,
context = “action alias”, appendPrefix = true)

CustomValidator Annotation: – This annotation uses this annotation for your custom validator types.

Eg: –  @CustomValidator(type =“customValidatorName”, fieldName = “myField”)

Type conversion annotations

By default, type conversion for Maps and Collections using generics is directly supported. Instead of defining the types found in collections and maps as documented in type conversion, the collection’s generic type is used. By using annotations, an application should be able to avoid using any ClassName-conversion.properties files. To use annotation-based type conversion, annotate the class or interface with the conversion Annotation. The commonly used type conversion annotations are,

Conversion Annotation: – It is a marker annotation for type conversions at Type level.

Eg: –

@Conversion()
public class ConversionAction implements Action {
}

CreateIfNull Annotation: – This annotation used for collection and map types: Create the types within the Collection or Map, if null. The CreateIfNull annotation must be applied at field or method level.

Eg: –

@CreateIfNull( value = true )
private List<User> users;

Element Annotation: – This annotation used for generic types: Specify the element type for Collection types and Map values. The Element annotation must be applied at field or method level.

Eg: –

// The key property for User objects within the users collection is the <code>userName</code> attribute.
@Element( value = com.acme.User )
private Map<Long, User> userMap;
@Element( value = com.acme.User )
public List<User> userList;

Key Annotation: – This annotation used for Generic types: Specify the key type for Map keys. The Key annotation must be applied at field or method level.

Eg: –

// The key property for User objects within the users collection is the <code>userName</code> attribute.
@Key( value = java.lang.Long.class )
private Map<Long, User> userMap;
KeyProperty Annotation: - This annotation used for Generic types: Specify the key property name value.
Eg: - // The key property for User objects within the users collection is the <code>userName</code> attribute.
@KeyProperty( value = “userName” )
protected List<User> users = null;

TypeConversion Annotation: – This annotation used for class and application wide conversion rules. The TypeConversion annotation can be applied at property and method level

Eg: –

@Conversion()
public class ConversionAction implements Action {
private String convertInt;
private String convertDouble;
private List users = null;
private HashMap keyValues = null;
@TypeConversion(type=ConversionType.APPLICATION,converter= “com.j2eebrain.util.XWorkBasicConverter”)
public void setConvertInt( String convertInt ) {
this.convertInt = convertInt;
}
@TypeConversion(converter= “com.j2eebrain.util.XWorkBasicConverter”)
public void setConvertDouble( String convertDouble ) {
this.convertDouble = convertDouble;
}
@TypeConversion(rule= ConversionRule.COLLECTION,
converter= “java.util.String”)
public void setUsers( List users ) {
this.users = users;
}
@TypeConversion(rule = ConversionRule.MAP, converter = “java.math.BigInteger”)
public void setKeyValues( HashMap keyValues ) {
this.keyValues = keyValues;
}
@TypeConversion(type = ConversionType.APPLICATION, property= “java.util.Date”,
converter = “com.j2eebrain.util.XWorkBasicConverter”)
public String execute() throws Exception {
return SUCCESS;
}
}

This struts tutorial on the different types of struts 2 annotation has explained all the struts 2 annotations with examples.