Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Annotations 
3.
Creating a Project👨‍🏫
4.
Configuration of pom.xml
5.
Configure web.xml file 
6.
Action Class 💥
6.1.
Add Image Files
6.2.
Entities Class
7.
View Page
8.
Redirect Page 👨‍🏫
9.
Run the Application👍
10.
Output ✅
11.
Frequently Asked Questions
11.1.
What is Struts2?
11.2.
Describe a few functional annotations that Struts2 included.
11.3.
What are the recommended practices for creating applications using Struts 2?
11.4.
What are Struts2 core components?
11.5.
What are the different ways of creating Action classes in Struts2?
12.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts2 Annotations Example

Author Gunjan Batra
0 upvote

Introduction

In this article, we will try to understand the annotations in Struts. We will further see how these annotations help us in achieving zero configuration. We will develop an application where we will be analysing the importance of these annotations in Struts2.

Annotations in struts2 help check the file's error and make our applications faster.

Types of Annotations 

There are two methods to use the zero configuration file(no struts.xml file) annotation and the by convention method.

Various annotations are present in Struts2, but we will use a few to develop a simple application.

Annotations img

🔥 @Result: Result annotation gives the result in the action class rather than the XML file.

🔥@Namespace: It allows you to define the action namespace in the action class.

🔥@Action: It allows the programmer to execute an action for the view page. 

🔥@Results: It gives multiple results for a single action.

🔥@Before: This annotation helps execute the method before the action method.

🔥@After:  This marks the technique to be executed after the main action method results are out.

🔥@RequiredStringValidator: This validation checks that the string is not null and has a length>0.
There are many other annotations, but in this blog, we will try to understand some majorly used annotations in the project to get a clear idea of how these annotations work.

Creating a Project👨‍🏫

Application image

You start with creating a maven project. Add the tomcat server and also the JRE system library. Here, you will create an application where you will use the annotation to redirect your page and run the class of your annotated method.

The application will follow this file Structure.

Structure image

You need to create five files for struts annotated application:

  1. pom.xml
  2. web.xml file
  3. Action class
  4. Create View page
  5. Result page

Configuration of pom.xml

Configure the pom.xml file below: This file helps you download the required jars and dependencies to run the project.

<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>Struts2Annotation</groupId>
  <artifactId>Struts2Example</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Struts2Example 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>Struts2Example</finalName>
 </build>

</project>

Configure web.xml file 

Open the web.xml file in the src\main\webapp\WEB-INF folder and add the struts2 configuration as given 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>LearnStruts2Annotations</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 Class 💥

Now you will create the action class. Refer to the file structure and make the DemoAction.java file in the controllers.action package.

The code is shown below.

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;
import entities.Product;


@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;
 }
}

Add Image Files

Create the folder according to the folder structure and copy the image you will use in the project to the images folder.

Entities Class

To get the entities for your action class, create the entities as shown.

package entities;

public class Product {
 private String id;
 private String name;
 private String photo;
 private double price;
 private int quantity;
 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getPhoto() {
  return photo;
 }

 public void setPhoto(String photo) {
  this.photo = photo;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }

 public int getQuantity() {
  return quantity;
 }

 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }

 public Product() {
 }

 public Product(String id, String name, String photo, double price, int quantity) {
  this.id = id;
  this.name = name;
  this.photo = photo;
  this.price = price;
  this.quantity = quantity;
 }
}

View Page

 We will create the view page to create the display on the page. Refer to the folder structure and create the JSP file as an 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 Annotation</title>
</head>
<body>
 <h3>Product Info</h3>
 <table border="1" cellpadding="2" cellspacing="2">
  <tr>
   <td>Id</td>
   <td>${product.id }</td>
  </tr>
  <tr>
   <td>Name</td>
   <td>${product.name }</td>
  </tr>
  <tr>
   <td valign="top">Photo</td>
   <td><img src="${pageContext.request.contextPath }/assets/images/${product.photo }" width="120"></td>
  </tr>
  <tr>
   <td>Price</td>
   <td>${product.price }</td>
  </tr>
  <tr>
   <td>Quantity</td>
   <td>${product.quantity }</td>
  </tr>
  <tr>
   <td>Total</td>
   <td>${product.price * product.quantity }</td>
  </tr>
 </table>
</body>
</html>

Redirect Page 👨‍🏫

Create a new jsp file as index.jsp in src\main\webapp folder..

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

Run the Application👍

Select the project, right-click and select Run on Server.

Access index method in demo action with the following URL.

http://localhost:8080/LeranStrutsFramework/demo/index.html

Output ✅

Your application is ready by using the annotations in struts2.

output

Frequently Asked Questions

What is Struts2?

Apache Struts2 is an open-source framework for building web applications in java.

It is far better than struts 1, increasing flexibility and usability. We have many tags and some new additional features like type convertors which make it easily extensible.

Describe a few functional annotations that Struts2 included.

Some of the essential annotations that were introduced in struts2 are:

@Action, @Namespace, @Result, @ResultPath, @Actions, etc. These are some of a few annotations that are used in every application of Struts2.

What are the recommended practices for creating applications using Struts 2?

Attempt always to extend the struts-default package when establishing your package. To prevent code repeatedly while using interceptors, For code reuse and ModelDriven interface implementation, action classes' Java bean properties should always be kept in a distinct bean.

What are Struts2 core components?

Struts2 core components are:

Action classes, Interceptors, Result pages, Tag libraries, and JSP, are some of the few core components.

What are the different ways of creating Action classes in Struts2?

For Creating Action classes, we use four methods. These four methods are described below:

By implementing an action interface, using Struts2 @Action annotations, any regular Java class containing an execute method and a String return value may be set up as an action class, and by adding to the ActionSupport class.

Conclusion

In this blog, we started by introducing the annotations in struts2. Annotations help you in achieving zero configuration files. Then we learned how these annotations are applied in the code. We also learn some most common use annotations. Ultimately, in the end, we try to create an application to get more insights into annotations that are used in real life.

Check this link if you want to learn more about java frameworks. If you are preparing for the upcoming placements, don’t worry. 

Click here for a carefully crafted and designed course on on-campus placements and interview preparation.

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

Happy Learning, Ninjas!

Thankyou
Live masterclass