Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction🤔
2.
Struts 2 Annotation Types🎯
2.1.
Namespace Annotation💻
2.2.
Result Annotation👨🏻‍💻
2.3.
Results Annotation💻
2.4.
After Annotation👨🏻‍💻
2.5.
Before Annotation🤔
2.6.
BeforeResult Annotation👨🏻‍💻
2.7.
ConversionErrorFieldValidator Annotation💻
2.8.
DateRangeFieldValidator Annotation🖥️
2.9.
DoubleRangeFieldValidator Annotation🤔
2.10.
EmailValidator Annotation💻
2.11.
ExpressionValidator Annotation🤔
2.12.
IntRangeFieldValidator Annotation💻
2.13.
RegexFieldValidator Annotation👨🏻‍💻
2.14.
RequiredFieldValidator Annotation💻
2.15.
RequiredStringValidator Annotation💻
2.16.
StringLengthFieldValidator Annotation🤔
2.17.
UrlValidator Annotation💻
2.18.
Validations Annotation💻
2.19.
CustomValidator Annotation🤔
2.20.
Conversion Annotation💻
2.21.
CreateIfNull Annotation👨🏻‍💻
2.22.
Element Annotation🤔
2.23.
Key Annotation💻
2.24.
KeyProperty Annotation👨🏻‍💻
2.25.
TypeConversion Annotation🤔
3.
Frequently Asked Questions
3.1.
What are the Struts 2 Annotations?
3.2.
What are the Struts 2 core components?
3.3.
What is Struts XML?
3.4.
What is Conversion Annotation?
3.5.
What is IntRangeFieldValidator Annotation?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Struts 2 Annotations Types

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. 

struts coding ninjas

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. 

struts 2 annotation types

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. 🤗

Frequently Asked Questions

What are the Struts 2 Annotations?

The standard method is to utilise the struts.xml file for all settings. The Java 5 Annotations feature may also be used to configure Struts. We may accomplish Zero Configuration by using the struts annotations.

What are the Struts 2 core components?

The three major Struts2 building components are the Action, Interceptor, and Result pages. Struts2 allows you to define and customise action classes in various ways.

What is Struts XML?

The struts.xml file contains the configuration data that will be changed when actions are generated. DevMode = false, as well as other default parameters provided in property files, can be altered for an application that uses this file, such as struts.

What is Conversion Annotation?

This is a type conversion marker annotation at the Type level. Conversion annotations must be used at the Type level.

What is IntRangeFieldValidator Annotation?

This validation annotation ensures that a numeric field has a value within a specific range. Nothing will be done if neither min nor max is set.

Conclusion

In this article, we have extensively discussed the Struts 2 Annotations Types. 

Do you not feel eager to read/explore additional information on the subject of Struts 2 after reading about the Struts 2 Annotations Types? See the Struts 2 documentationStruts Tutorial for beginnersStruts 2 Intro, and 15 Best Java frameworks to use in 2022-Coding Ninjas.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Learning Ninja!🥷

coding ninjas
Live masterclass