Introduction🤔
Apache Struts 2 is a sophisticated, flexible framework for developing enterprise-class Java web applications. This framework is intended to simplify the whole development cycle, from application creation through deployment and maintenance over time. This framework provides alternatives to XML and Java properties.
This blog will go through the Struts 2 annotation types and a list of the essential annotations related to different categories. Let’s go, Ninja!🫡
Struts 2 Annotation Types🎯
Struts 2 is a versatile framework for creating enterprise-level Java web applications. This framework is meant to streamline the development cycle, from application conception to deployment and ongoing maintenance. Java 5 annotations can be used as an alternative to XML and Java property settings in Struts 2 applications.
Let us discuss some of the essential annotation types related to different categories.
Namespace Annotation💻
The @Namespace annotation type allows the namespace of an Action to be defined in the Action class rather than using Zero Configuration standards.
@Namespace("/content")
public class Employee extends ActionSupport{
...
}
Result Annotation👨🏻💻
The @Result annotation type allows Action results to be defined in the Action class rather than an XML file.
@Result(name = "success", value = "/success.jsp")
public class Employee extends ActionSupport{
...
}
Results Annotation💻
The @Results annotation type specifies a list of Action results.
@Results({
@Result(name = "success", value = "/success.jsp"),
@Result(name = "error", value = "/error.jsp")
})
public class Employee extends ActionSupport{
...
}
After Annotation👨🏻💻
The @After annotation type denotes an action method that must be called after the primary action method has been completed and the result has been performed. The return value is unimportant.
public class Employee extends ActionSupport{
@After
public void isValid() throws ValidationException {
// validate a model object, throw an exception if failed
}
public String execute() {
// perform secure action
return SUCCESS;
}
}
Before Annotation🤔
The @Before annotation type indicates that an action method must be called before the main action method and the result was executed. The return value is unimportant.
public class Employee extends ActionSupport{
@Before
public void isAuthorized() throws AuthenticationException {
// authorize the request, throw an exception if failed
}
public String execute() {
// perform secure action
return SUCCESS;
}
}
BeforeResult Annotation👨🏻💻
The @BeforeResult annotation type denotes an action method that must be run before the result. The return value is unimportant.
public class Employee extends ActionSupport{
@BeforeResult
public void isValid() throws ValidationException {
// validate a model object, throw an exception if failed
}
public String execute() {
// perform action
return SUCCESS;
}
}
ConversionErrorFieldValidator Annotation💻
This validation annotation type checks for conversion problems in a field and applies them if any are found.
public class Employee extends ActionSupport{
@ConversionErrorFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getName() {
return name;
}
}
DateRangeFieldValidator Annotation🖥️
This validation annotation type verifies that a date field contains a value within a specific range.
public class Employee extends ActionSupport{
@DateRangeFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true,
min = "2005/01/01", max = "2005/12/31")
public String getDOB() {
return dob;
}
}
DoubleRangeFieldValidator Annotation🤔
This validation annotation type verifies that a double field's value is inside a particular range. Nothing will be done if neither min nor max is set.
public class Employee extends ActionSupport{
@DoubleRangeFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true,
minInclusive = "0.123", maxInclusive = "99.987")
public String getIncome() {
return income;
}
}
EmailValidator Annotation💻
If a field has a non-empty String, this validation annotation type determines it is a legitimate e-mail address.
public class Employee extends ActionSupport{
@EmailValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getEmail() {
return email;
}
}
ExpressionValidator Annotation🤔
This non-field level validator verifies a regular expression given.
@ExpressionValidator(message = "Default message", key = "i18n.key",
shortCircuit = true, expression = "an OGNL expression" )
IntRangeFieldValidator Annotation💻
This validation annotation type ensures that a numeric field has a value within a specific range. Nothing will be done if neither min nor max is set.
public class Employee extends ActionSupport{
@IntRangeFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true,
min = "0", max = "42")
public String getAge() {
return age;
}
}
RegexFieldValidator Annotation👨🏻💻
This annotation type uses a regular expression to verify a string field.
@RegexFieldValidator( key = "regex.field", expression = "yourregexp")
RequiredFieldValidator Annotation💻
This validation annotation type ensures that a field is not empty. The annotation should be used at the method level.
public class Employee extends ActionSupport{
@RequiredFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getAge() {
return age;
}
}
RequiredStringValidator Annotation💻
This validation annotation type ensures that a String field is not empty (that it is non-null and has a length greater than 0).
public class Employee extends ActionSupport{
@RequiredStringValidator(message = "Default message",
key = "i18n.key", shortCircuit = true, trim = true)
public String getName() {
return name;
}
}
StringLengthFieldValidator Annotation🤔
This validator ensures that a String field is a correct length. It is assumed that the field is of type String. Nothing is done if neither minLength nor maxLength is specified.
public class Employee extends ActionSupport{
@StringLengthFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true,
trim = true, minLength = "5", maxLength = "12")
public String getName() {
return name;
}
}
UrlValidator Annotation💻
This validator verifies that a field has a valid URL.
public class Employee extends ActionSupport{
@UrlValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getURL() {
return url;
}
}
Validations Annotation💻
If you wish to utilise several annotations of the same kind, you must nest them within the @Validations() annotation.
public class Employee extends ActionSupport{
@Validations(
requiredFields =
{@RequiredFieldValidator(type = ValidatorType.SIMPLE,
fieldName = "customfield",
message = "You must enter a value for the field.")},
requiredStrings =
{@RequiredStringValidator(type = ValidatorType.SIMPLE,
fieldName = "stringisrequired",
message = "You must enter a value for the string.")}
)
public String getName() {
return name;
}
}
CustomValidator Annotation🤔
This annotation helps create custom validators. To provide extra parameters, use the ValidationParameter annotation.
@CustomValidator(type ="customValidatorName", fieldName = "myField")
Conversion Annotation💻
This is a type conversion marker annotation at the Type level. Conversion annotations must be used at the Type level.
@Conversion()
public class ConversionAction implements Action {
}
CreateIfNull Annotation👨🏻💻
This annotation specifies the CreateIfNull type conversion annotation. CreateIfNull must be applied at the field or method level.
@CreateIfNull( value = true )
private List<User> users;
Element Annotation🤔
This annotation marks the Element as ready for type conversion. Element annotations must be used at the field or method level.
@Element( value = com.acme.User )
private List<User> userList;
Key Annotation💻
This annotation sets the Key for type conversion. The Key annotation should be used at the field or method level.
@Key( value = java.lang.Long.class )
private Map<Long, User> userMap;
KeyProperty Annotation👨🏻💻
This annotation sets the KeyProperty for type conversion. KeyProperty annotations must be used at the field or method level.
@KeyProperty( value = "userName" )
protected List<User> users = null;
TypeConversion Annotation🤔
This annotated annotation is used for application and class-wide conversion rules. The TypeConversion annotation can be used on both properties and methods.
@TypeConversion(rule = ConversionRule.COLLECTION,
converter = "java.util.String")
public void setUsers( List users ) {
this.users = users;
}
We hope you understood everything about struts 2 annotation types. 🤗