Configure the struts.xml to support return JSON data
The package must extends
struts-default,json-default
Must define below result
<result name="success" type="json">
<param name="root">dataMap</param>
</result>
Sample configuration in struts.xml
<package extends="struts-default,json-default" name="friendLink" namespace="/friendLink">
<action class="friendLinkAction" method="{1}" name="friendLink_*">
<result name="success" type="json">
<param name="root">dataMap</param>
</result>
</action>
</package>
Your action java class must define below property
private Map<String, Object> dataMap = new HashMap<String, Object>();
public Map<String, Object> getDataMap() {
return dataMap;
}
public void setDataMap(Map<String, Object> dataMap) {
this.dataMap = dataMap;
}
Sample code in action class
public void login(){
dataMap.put("status", 200);
dataMap.put("message", "login success");
return "success";
}
// The client side will receive the JSON data
//{"status":200, "message":"login success"}
Add JSON annotation to convert the date field
Default the date may show like 2016-01-01T12:45:12
You can add @JSON(format=”yyyy-MM-dd HH:mm:ss”) or @JSON(format=”yyyy-MM-dd”) to the getter method
Sample code show below:
import org.apache.struts2.json.annotations.JSON;
@JSON(format="yyyy-MM-dd HH:mm:ss")
public Date getCreationDate() {
return creationDate;
}
Reference
Related Jars:
struts2-json-plugin-2.3.28.1.jar
struts2-core-2.3.28.1.jar
jackson-databind-2.6.4.jar
jackson-core-2.6.4.jar
jackson-annotations-2.6.4.jar