Struts 2 Annotations Example


Struts 2 gives you helpful approach to make struts application utilizing comments. In this way, there is no need struts.xml file.

As we have said before, there are 2 different ways to utilize zero design record (no struts.xml file).

  1. By convention
  2. By annotation

Annotations utilized in struts 2 application

For basic explanation case of struts 2, we can utilize 3 annotations:

1) @Action explanation is utilized to check the activity class.

2) @Results explanation is utilized to characterize numerous outcomes for one action.

3) @Result comment is utilized to show single result.


Example of struts 2 application utilizing annotations

You need to make 4 documents for struts commented on 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. }  





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition