Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Jar Required in Projects 👨‍💻
3.
Annotations in Struts2
3.1.
💥@Action Annotation
3.2.
💥@Results Annotation
3.3.
💥@Result Annotation
4.
Creating an Application
5.
Pom.xml File💻
6.
Web.xml File💻
7.
Action Page💻
8.
View Page 💻
9.
Redirect Page💻
10.
Run the Application✅
11.
Frequently Asked Questions 
11.1.
What are Struts2 Annotations?
11.2.
How can you achieve zero configuration in Struts2?
11.3.
Why is the Struts framework used?
11.4.
 What is ActionSupport in Struts2?
11.5.
What is the advantage of Struts2 over Struts1?
12.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts 2 Annotations

Author Gunjan Batra
0 upvote

Introduction 

In this article, we will explore the annotations in Struts2. We will further see how these annotations help in configuration and help in zero configuration.

Struts

The Java 5 Annotations feature is the other method of customizing Struts. You can easily construct struts applications using Struts 2 by utilizing annotations. Therefore, having a struts.xml file is not required.

Jar Required in Projects 👨‍💻

Many jars are needed to install in the lib file. These jars are listed below.  

  • struts2-convention-plugin-x.y.z.jar
  • asm-x.y.jar
  • antlr-x.y.z.jar
  • commons-fileupload-x.y.z.jar
  • commons-io-x.y.z.jar
  • commons-lang-x.y.jar
  • commons-logging-x.y.z.jar
  • commons-logging-api-x.y.jar
  • freemarker-x.y.z.jar
  • javassist-.xy.z.GA
  • ognl-x.y.z.jar
  • struts2-core-x.y.z.jar
  • Xwork-core.x.y.z.jar

You can download these jars from the link mentioned. Essential dependencies

Annotations in Struts2

Annotations

Do not worry! We are here for you.

Different Annotations are present in Struts2, which are discussed below.

Annotations

Description 

@Result Single results is given using the result annotation. It provides the output in the action class.
@Action Defines the URL for the action class, and the class identification is made by action annotation.
@Namespace The part of the action URL between the context path and the action name, as indicated by namespace annotation, should be specified.

@RequiredFieldValidator

 

It checks that the field is not null. It is applied at the method level.are
@BeforeResult It is used to call the method before the result is called.
@After It calls the action method after the primary method and when the outcome is executed.
@Results It defines the set of results.
@EmailValidator This annotation checks for the email address's validity and contains an empty string.
@RequiredStringValidator It checks that the string is not null and has a length > 0.
@TypeConversion It is applicable at the property and method levels.

@ConversionErrorFieldValidator Annotation

 

This annotation checks for validation in a field and conversion mistakes and fix them.
@KeyProperty Sets the key property for type conversion. 
@BeforeResult This makes the action class execute the method before the result is out.

@DateRangeFieldValidator 

 

It checks whether the date field is in the range or not.

@DoubleRangeFieldValidator

 

This checks that the double field has a  value that matches the desired content. If min and max are not set, nothing will be done.

@ExpressionValidator

 

This non-field level validator validates a supplied regular expression.

 

@IntRangeFieldValidator This validator ensures a numeric field contains a value that falls inside a predetermined range. No action will be taken if neither the min nor the max is set.

@StringLengthFieldValidator

 

It looks that the string is of the desired length. If min, maximum is not set, nothing is done.

Some of the popularly used annotations are shown in the code below.

💥@Action Annotation

It is used to define the action class. 

When the action link value equals the value of the Action annotation, Struts 2 perform the annotated method.

@Namespace(“/demo”)
public class DemoAction extends ActionSupport {

 private static final long serialVersionUID = 1L;

 private Product product;

 public Product getProduct() {
  return product;
 }

 public void setProduct(Product product) {
  this.product = product;
 }

 @Action(value = "index", results = {
  @Result(name = SUCCESS, location = "/WEB-INF/views/demo/index.jsp")
 })
 
 public String index() {
  this.product = new Product("p01", "name 1", "thumb1.gif", 2, 4);
  return SUCCESS;
 }

}

💥@Results Annotation

It defines the multiple results for a single action. When the class has multiple values to return, we use results annotations so that you can receive the value that is returned by the method.

@Results({
   @Result(name = "success", value = "/success.jsp"),
   @Result(name = "error", value = "/error.jsp")
})
public class DemoAction extends ActionSupport{
 ...
}

💥@Result Annotation

It defines the result for a single unit. We use the annotation result when the action class returns a single value. The above method gives you the ease that you can receive the returned value of the class.

@namespace(“/demo”)
  @Result(name = SUCCESS, location = "/WEB-INF/views/demo/index.jsp")
public class DemoAction extends ActionSupport {
….}

Creating an Application

start img

Now, we will create the application using these annotations. For creating the web application, you need to configure your two files: Pom.xml and webx.xml. Make sure you create the folder and file in the same directory shown in the picture below:

Structure img

Pom.xml File💻

 Configure pom.xml file and add configurations for strust2 as below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.gunjan</groupId>
  <artifactId>LearnStrutsFramework</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>LearnStrutsFramework Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet.jsp.jstl</groupId>
   <artifactId>javax.servlet.jsp.jstl-api</artifactId>
   <version>1.2.1</version>
  </dependency>

  <dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
  </dependency>
  
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>

  <!-- Struts 2 Framework -->

  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-core</artifactId>
   <version>2.5.20</version>
  </dependency>

  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-convention-plugin</artifactId>
   <version>2.5.20</version>
  </dependency>
    
  </dependencies>
  <build>
    <finalName>LearnStrutsFramework</finalName>
  </build>
</project>

Web.xml File💻

Configure web.xml in src\main\webapp\WEB-INF folder and add the configurations as shown below:
 

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> 
<display-name>Learn Struts 2 Framework</display-name> 
<filter> 
<filter-name>struts2</filter-name> 
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> 
<init-param> <param-name>struts.devMode</param-name> 
<param-value>true</param-value> 
</init-param> 
<init-param> <param-name>struts.action.extension</param-name>
 <param-value>html</param-value> </init-param> 
 </filter> 
 <filter-mapping> 
 <filter-name>struts2</filter-name> 
 <url-pattern>/*</url-pattern> 
 <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
   <dispatcher>INCLUDE</dispatcher> 
   </filter-mapping>
    <welcome-file-list> <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>

Action Page💻

Now you create the action page. The action page helps the JSP determine which class or method to run.

package Controllers.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/demo")
public class DemoAction extends ActionSupport {
 
 private static final long serialVersionUID = 1L;
 private int age;
 private String username;
 private double price;
 private boolean status; 
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 } 
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 public boolean isStatus() {
  return status;
 }
 public void setStatus(boolean status) {
  this.status = status;
 }
 @Action(value = "index", results = {
  @Result(name = SUCCESS, location = "/WEB-INF/views/demo/index.jsp")
 })
 public String index() {
  this.age = 20;
  this.username = "abc";
  this.price = 4.5;
  this.status = true;
  return SUCCESS;
 } 
}

View Page 💻

After creating the action page, you will create the view page for the application. Name this file as index.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1" isELIgnored="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body> 
 Age: ${age }
 <br>
 Username: ${username }
 <br>
 Price: ${price }
 <br>
 Status: ${status }
</body>
</html>

Redirect Page💻

 After creating the view page for the application, you will need to redirect your page to index.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 <jsp:forward page="demo/index.html"></jsp:forward>

Run the Application✅

To run the application, select the project, right-click and select Run on Server menu.

Access Index method in demo action with this URL.

Output img

Frequently Asked Questions 

What are Struts2 Annotations?

Struts2 provides you with the feature of annotations so that you can achieve zero configuration. It is an alternative for the struts.xml files. With annotations, you can quickly eliminate the XML file configuration. Annotations give you an easy way to create an application.

How can you achieve zero configuration in Struts2?

To achieve zero configuration in Struts2, we use the java five feature, i.e., annotations. 

These annotations help us to define the action class, the view, and the redirection page. It reduces the struts.xml file in your project.

Why is the Struts framework used?

Struts2 is an open-source framework that extends the Java Servlet API and supports the MVC structure. It helps us to create Java EE applications flexibly and efficiently. It supports the model, view, and controller by which the application is maintainable.

 What is ActionSupport in Struts2?

This class provides you with default implementations for the common actions that you performed. It has an implementation of several functional struts2 interfaces. In struts, the action class is POJO which means you are not forced to implement any interfaces or methods.

What is the advantage of Struts2 over Struts1?

In Struts1, all the class properties are of type string, whereas in Struts2, it can be of any type. In Struts2, the use of annotation is flexible and accessible. The APIs are loosely coupled, which makes the testing more accessible.

Conclusion

Congratulations on finishing the blog!!

In this blog, we started with what are annotations and their types. Then we learned how these annotations work with the code. We also learned how these annotations help in zero configurations, and in the end, we have seen how different annotations help create an application. To get more insights about java frameworks, refer to our blog Java Frameworks.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning, Ninjas!

Thankyou
Live masterclass