Struts2 returns Json data (using the Struts2 plug-in)
1. The main steps are as follows: 1. copy the struts2-json-plugin.jar plug-in to the project's "/WEB-INF/lib" folder; 2. write Action files. 3. in struts. configure the Action in the xml file. The "<package... /> "must inherit" json-default ". The Result type of the Action is json, that is, type =" json ", and does not correspond to any view resource. Ii. Sample Code: Action file: package com. example. action; import java. util. arrayList; import com. opensymphony. xwork2.ActionSupport; public class StrutsJsonAction extends ActionSupport {private int I = 123; private String str = "str"; private int [] array = {1, 2, 3 }; private ArrayList <String> list; public int getI () {return I;} public void setI (int I) {this. I = I;} public String getStr () {return str;} public v Oid setStr (String str) {this. str = str;} public int [] getArray () {return array;} public void setArray (int [] array) {this. array = array;} public ArrayList <String> getList () {return list;} public void setList (ArrayList <String> list) {this. list = list;} public String execute () {list = new ArrayList <String> (); list. add ("red"); list. add ("green"); list. add ("yellow"); return SUCCESS;} struts. Xml file: <? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name = "json-example" namespace = "/ "extends =" json-default "> <action name =" JSONExample "class =" com. example. action. strutsJsonAction "> <result name =" success "type =" json "/> </action> </package> </struts> the JSON plug-in serializes all serializable Action attributes JSON data. 3. Configure the Result of the JSON type: serialized attributes: <result type = "json"> <! -- Disable browser cache --> <param name = "noCache"> true </param> <! -- Set the server response type --> <param name = "contentType"> application/json </param> <! -- All matching expression attribute names will be serialized --> <param name = "includeProperties"> I, str </param> </result> only serialize the specified Action attribute: <result type = "json"> <! -- Disable browser cache --> <param name = "noCache"> true </param> <! -- Set the server response type --> <param name = "contentType"> application/json </param> <! -- Only serialize the specified attribute in the Action --> <param name = "root"> list </param> </result>