Struts 2 Annotations Example

Struts 2 Zero Configuration by convention example tutorial. We can create the struts 2 application without using the struts.xml file by following convention.

Struts 2 Annotations Example

Struts 2 Annotations Example

Struts 2 provides you a convenient way to create struts application using annotations. So, there is no need to have struts.xml file.

As we have said earlier, there are 2 ways to use zero-configuration file (no struts.xml file).

  1. By convention
  2. By annotation

Annotations used in struts 2 application

For simple annotation example of struts 2, we can use 3 annotations:

1) @Action annotation is used to mark the action class.

2) @Results annotation is used to define multiple results for one action.

3) @Result annotation is used to display single result.


Example of struts 2 application using annotations

You need to create 4 files for struts annotated application:

  1. index.jsp
  2. Action class
  3. struts.properties inside src directory
  4. Result page
  5. web.xml file

Let's have a look at the directory structure first.

1) Create index.jsp for input

This jsp page creates a form using struts UI tags that receives name from the user.

index.jsp

  1. <%@ taglib prefix="s" uri="/struts-tags" %>  
  2.   
  3. <s:form action="myAction" >  
  4. <s:textfield name="name" label="Name" />  
  5. <s:submit />  
  6. </s:form>  

2) Create the action class

This action class uses the annotations for the action and result.

RegisterAction.java

  1. package mypack;  
  2. import org.apache.struts2.convention.annotation.*;  
  3.   
  4. @Action(value="myAction",results={@Result(name="ok",location="/myResults/result.jsp")})  
  5. public class MyAction {  
  6. private String name;  
  7. public String getName() {  
  8.     return name;  
  9. }  
  10. public void setName(String name) {  
  11.     this.name = name;  
  12. }  
  13. public String execute()  
  14. {  
  15. return "ok";      
  16. }  
  17. }  

3) Create struts.properties file inside src directory

struts.properties

  1. struts.convention.package.locators=mypack  
  2. struts.convention.result.path=/myResults  
  3. struts.convention.action.mapAllMatches=true  

4) Create result.jsp to display message

This jsp page displays the username.

result.jsp

  1. <%@ taglib prefix="s" uri="/struts-tags" %>  
  2. Hello, <s:property value="name" /> It is annotated application.