1. A required package. One package must be unique !!
Json-lib-2.3-jdk15.jar
Struts2-json-plugin-2.3.3.jar
Commons-beanutils-1.8.3.jar,
Commons-collections-3.2.1.jar,
Commons-logging-1.1.1.jar,
Commons-logging-1.1.1.jar,
Ezmorph-1.0.6.jar (if this package is missing, it can easily lead to strange problems, such as execution midway out)
2. Struts. xml
<! -- A default space JSON-default is inherited here --> <package name = "jsondemo" extends = "JSON-Default"> <action name = "jsonaction" class = "action. jsondemo "> <! -- The return type is JSON --> <result type = "JSON"> <! -- Name must be root, result is the property name to be returned to the foreground in action --> <Param name = "root"> result </param> </result> </Action> </package>
3. ActionCode
Public class jsondemo implements action {// attributes used for data transmission private string name; private string result; private muer mm; Public String execute () throws exception {// todo auto-generated method stubsystem. out. println ("action"); Mm = new muer (); mm. setage ("20"); mm. setname (name); mm. setlevel ("very beautiful"); system. out. println ("Age" + mm. getage () + "name:" + mm. getname () + "level:" + mm. getlevel (); jsonobject OBJ = jsonobject. fromobject (mm); Result = obj. tostring (); system. out. println ("JSON string:" + result); Return success ;}
// Skip the getter and setter methods of each attribute}
4. jsp page
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" S "uri ="/Struts-tags "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
To sum up, pay attention to the following points:
1. There should be no less than one package...
2. The data sent back by the action must be processed once. var Mm = eval ("(" + Data + ")");
3. You can call the MM. Name object after eval processing to obtain the attributes.
Supplement: struts2 uses JSON to pass the list set to the foreground page:
// Obtain the database location ajaxpublic string getlgortbybukrs () {try {// system. out. println (bukrs); // here, a list set list <t001l> lgortlist = t001lservices is obtained through the service class. getlgortbybukrs (bukrs); // converts the list set to jsonarray object jsonarray jarray = jsonarray. fromobject (lgortlist); // convert to JSON string result = jarray. tostring (); // system. out. println (result); Return success;} catch (exception e) {e. printstacktrace ();} return NULL ;}