How can we access form data in struts2?

In Struts2, it is possible to use the properties of an Action class to receive form data. One common approach is as follows:

  1. Define properties in the Action class that correspond to the fields in the form. For example, if there is a field named “username” in the form, you can define a String type property named “username” in the Action class.
public class MyAction extends ActionSupport {
    private String username;

    // getter and setter methods for username

    public String execute() {
        // TODO: 处理表单数据
        return SUCCESS;
    }
}
  1. Can you provide me with the code for the form?
  2. Please enter your text in the field.
<s:form action="myAction">
    <s:textfield name="username" label="Username" />
    <s:submit value="Submit" />
</s:form>
  1. implement
public String execute() {
    // 使用属性值处理表单数据
    System.out.println("Username: " + username);
    return SUCCESS;
}

In the example above, when a user submits the form, Struts2 will automatically set the value of the “username” field to the “username” property in the Action class. You can access this property within the execute() method to retrieve the form data.

bannerAds