How can Struts2 receive JSON data?
Struts2 has the ability to receive JSON data by using the JSON plugin. Below are the steps for receiving JSON data.
- Firstly, make sure you have already included the struts2-json-plugin plugin in your project. You can either do this through Maven or by manually downloading and importing the plugin.
- Add the following configuration in the Struts2 configuration file (usually struts.xml).
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="json" extends="json-default">
<action name="yourAction" class="com.yourpackage.YourAction">
<result type="json" />
</action>
</package>
In the above configuration, yourAction refers to the designated Action name, while com.yourpackage.YourAction refers to the designated Action class.
- In the Action class, add a property for receiving JSON data and the corresponding getter and setter methods. For example:
private Map<String, Object> jsonData;
public Map<String, Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String, Object> jsonData) {
this.jsonData = jsonData;
}
- Can you provide the JSON data?
@Action(value = "yourAction", results = { @Result(name = "success", type = "json") })
public String execute() {
// 在这里处理接收到的JSON数据
System.out.println(jsonData);
return "success";
}
In the above example, the jsonData attribute stores the received JSON data as a Map object and prints it out during the execution of the method.
- Send a request to Action containing JSON data. You can use tools like AJAX or Postman to send an HTTP request and include JSON data in the request body.
After completing the above steps, Struts2 will automatically convert the received JSON data into the specified property types and use them in the execute method.