ways to create Action classes in Struts2

ways to create Action classes in Struts2

Struts2 allows for flexibility in creating Action classes, catering to various needs and architectural preferences. Here are the primary methods:

ways to create Action classes in Struts2

1.  Implementing Action Interface

2.  Extending ActionSupport Class

3.  Using Annotations

Explanation and Java Examples

1.  Implementing Action Interface

This approach involves directly implementing the Action interface provided by Struts2. It requires implementing the execute() method to handle the action logic.

Java Example
java
package com.example.action;

import com.opensymphony.xwork2.Action;

public class HelloWorldAction implements Action {

    @Override
    public String execute() throws Exception {
        // Action logic here
        return "success";
    }
}

2.  Extending ActionSupport Class

ActionSupport is a convenient base class provided by Struts2 that implements the Action interface. It provides additional utility methods and simplifies common actions.

Java Example
java
package com.example.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {

    @Override
    public String execute() throws Exception {
        // Action logic here
        return SUCCESS;
    }
}

3.  Using Annotations

Annotations provide a declarative way to define actions and their properties, reducing the need for XML configuration. Annotations are available starting from Struts2 version 2.1.

Java Example
java
package com.example.action;

import com.opensymphony.xwork2.Action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

@Namespace("/example")
public class HelloWorldAction {

    @Action(value = "helloWorld", results = {
            @Result(name = "success", location = "/success.jsp")
    })
    public String execute() throws Exception {
        // Action logic here
        return "success";
    }
}

Conclusion

These methods provide flexibility and choice when developing Action classes in Struts2. Developers can choose based on project requirements, coding style preferences, and the level of configurability needed.