Struts 2 Annotations Example

 

To configure Struts 2 applications (action names, mapping, results,..), we can use either XML file (struts.xml) or annotations.

In this example, we will see how to use annotations in Struts 2 application to define and configure an action class.

 

1. Technologies used

  • Struts 2.3.16
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.6
  • Tomcat 6.0

 

2. Project structure

Struts2-Annotations-Example-1

 

3. Struts 2 dependencies

To use annotations, we need to add struts2-convention-plugin library to Maven’s pom.xml file.

File : pom.xml

 

4. Action classes

We will create two action classes :

LoginAction : to access the login page.

Equivalent config if we had used struts.xml :

 

HelloAction : to process login form and render back  hello.jsp page to the browser .

Equivalent config if we had used struts.xml:

 

4. JSP views

File :  index.jsp

 

File : hello.jsp

 

6. Test It

Index URL : http://localhost:8080/Struts2-Annotations-Example/Hello/login.action

Struts2-Annotations-Example-2

 

We enter some login and password and we press submit button :

Struts2-Annotations-Example-3

 

Download source code