STRUTS2 new JSON return type, automatically converts the member variable in the action to a JSON string

Source: Internet
Author: User


Made a small test struts2,spring,mybatis framework, the required jar package is as follows:



New result Type:json


Jsonresult.java


Package Com.test.xiaobc.login.server.util;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.io.ioexception;import Java.io.outputstream;import Java.lang.reflect.method;import Java.util.calendar;import Java.util.date;import Java.util.HashSet;import Java.util.set;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.lang.stringutils;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Org.apache.struts2.servletactioncontext;import Org.codehaus.jackson.jsongenerationexception;import Org.codehaus.jackson.map.jsonmappingexception;import Com.test.xiaobc.base.action.abstractaction;import Com.opensymphony.xwork2.actioninvocation;import Com.opensymphony.xwork2.result;import Com.opensymphony.xwork2.inject.inject;public class JsonResult implements result{/** inherit properties from Actionsupport */protected static final set<string> fields = new Hashset< String> ();p rivate static final long serialversionuid = 8840245761025613454l;private String defaultencoding = "UTF-8"; Private log log = Logfactory.getlog (GetClass ());p rivate String includeproperties;private set<string> includepropertiesset;/** * <action name= "findAll" class= "orderbillaction" method= "FindAll" > * <result name= ' Success ' type= ' json ' > * <param name= ' contentType ' >text/html</param> * </result> * </action> */private string contenttype;/** Serialization property, default to null replaced by empty string */private jsonfeature feature =    Jsonfeature.getdefaultjsonfeature ();/** * Call the JS function name */private String callbackparameter; static {Fields.Add ("actionerrors"); Fields.Add ("Actionmessages"); Fields.Add ("class"); Fields.Add ("Errormessages"); Fields.Add ("errors"); Fields.Add ("locale"); Fields.Add ("Fielderrors"); Fields.Add ("texts"); Fields.Add ("Success"); Fields.Add ("Isexception");}   @Inject ("struts.i18n.encoding") public void Setdefaultencoding (String val) {this.defaultencoding = val;} /**   * * <p> SET encoding format utf-8</p> * @date 2013-4-3 9:35:08 * @return * @see */protected String Gete Ncoding () {String encoding = this.defaultencoding;if (encoding = = NULL) {encoding = System.getproperty ("file.encoding");} if (encoding = = NULL) {encoding = "UTF-8";} return encoding;}    Public String getincludeproperties () {return includeproperties;}     /** * * <p> split contains properties file </p> * @date 2013-4-3 a.m. 9:35:39 * @param includeproperties * @see */public void Setincludeproperties (String includeproperties) {if (includeproperties = = null) {return;} This.includeproperties = includeproperties; String[] Properties = This.includeProperties.split (","); includepropertiesset = new hashset<string> (); for ( String property:properties) {Includepropertiesset.add (property);} This.setincludepropertieslist (Includepropertiesset);} Public set<string> getincludepropertieslist () {return includepropertiesset;} public void Setincludepropertieslist (SET&LT;STRIng> includepropertieslist) {this.includepropertiesset = includepropertieslist;} Public String getContentType () {return contentType;} public void setContentType (String contentType) {this.contenttype = ContentType;}    Public String Getfeature () {return feature.getfeature (); public void Setfeature (String feature) {if (Stringutils.isnotblank (feature) &&!this.feature.getfeature ().    Equals (feature)) {this.feature = new jsonfeature (feature); }}/** * Serialize the object into JSON * * @param val * @param sb * @throws jsongenerationexception * @throws jsonmappingexception * @throws IOException */private void Serialize (Object val, StringBuilder sb) throws Jsongenerationexception, Jsonmappingexception, IOException {if (val = = null) {Sb.append (Feature.dofeature ()). Append (",");} else if (val instanceof Number | | Val instanceof Boolean) {sb.append (val.tostring ()). Append (",");} else if (val instanceof Date) {sb.append ((Long) ((date) val). GetTime ()). Append (",");} else if (Val InstaNceof Calendar) {sb.append ((Long) ((Calendar) val). GetTime (). GetTime ()). Append (",");} else {sb.append (    Feature.dofeature (Jsonhelps.tostring (val))). Append (",");}} /** * * <p> input json</p> * @date 2013-4-3 a.m. 9:37:10 * @param invocation * @throws Except Ion * @see Com.opensymphony.xwork2.result#execute (com.opensymphony.xwork2.ActionInvocation) */public void execute (Actioninvocation invocation) throws Exception {if (log.isdebugenabled ()) {Log.debug ("Begin Jsonresult");} HttpServletRequest request= servletactioncontext.getrequest (); HttpServletResponse response = Servletactioncontext.getresponse (); if (getcontenttype () = null) { Response.setcontenttype (This.getcontenttype ());} else {response.setcontenttype ("Application/json");} Response.setcharacterencoding (defaultencoding); StringBuilder sb = new StringBuilder (); Sb.append ("{"); Object obj = Invocation.getaction (); BeanInfo IP = introspector.getbeaninfo (Obj.getclass ()); propertydescriptor[] Pros = Ip.getpRopertydescriptors ()///For Success, isexception property special handling if (obj instanceof abstractaction) {//Here is the parent class action ( abstractaction) PropertyDescriptor spd = new PropertyDescriptor ("Success", Obj.getclass ()); Method SMD = Spd.getreadmethod (), Object success = Smd.invoke (obj),///Return success attribute name preceded and preceded by double quotation marks sb.append ("\" Success\ ""). Append (":"); Serialize (success, SB); PropertyDescriptor EPD = new PropertyDescriptor ("Exception", Obj.getclass ()); Method EMD = Epd.getreadmethod (), Object isexception = Emd.invoke (obj),///return Isexception attribute name preceded and preceded by double quotation marks sb.append ("\" Isexception\ ""). Append (":"); Serialize (Isexception, SB);} for (PropertyDescriptor Pro:pros) {if (Includepropertiesset! = null &&!includepropertiesset.contains ( Pro.getdisplayname ())) {continue;} Method method = Pro.getreadmethod (); if (Method! = null) {Object val = method.invoke (obj, new object[0]); String proname = Pro.getdisplayname (); if (Fields.contains (Proname)) {continue;} All property names of the returned request class are preceded and followed by double quotation marks sb.append ("\" "); Sb.append (Pro.getdisplayname ()); Sb.append (" \ ""); Sb.append (": "); Serialize (Val, SB);}} String result = "", if (Sb.length () > 1) {result = sb.substring (0, Sb.length ()-1);}    result = Result.concat ("}"); result = addcallbackifapplicable (request, result); OutputStream out = Response.getoutputstream (); Out.write ( Result.getbytes (defaultencoding)); Out.flush (); Out.close (); /** * Add JS method call * @date 2012-12-5 PM 3:35:43 * @param request * @param JSON * @return * @see */private String Addcallbackifa Pplicable (HttpServletRequest request, String JSON) {if ((callbackparameter! = null) && (callbackparameter.            Length () > 0) {String callbackname = Request.getparameter (Callbackparameter); if ((callbackname! = null) && (callbackname.length () > 0)) {json = Callbackname + "(" + JSON +            ")";    }} return JSON; }public void Setcallbackparameter (String callbackparameter) {this.callbackparameter = Callbackparameter;} Public String Getcallbackparameter () {REturn Callbackparameter; }}class jsonfeature {public static final String allow_null_replaced_empty = "Allow_null_replaced_empty";p ublic static Final string allow_null = "Allow_null";p ublic static final String regex_null = "[' \"]*null[' \ "]*";p ublic static final Stri  ng empty_string = "\" \ "";p ublic static final STRING null_string = "NULL"; static final jsonfeature defaultjsonfeature = new Jsonfeature (allow_null);p rivate string Feature;public jsonfeature (String feature) {this.feature = feature;} public static Jsonfeature Getdefaultjsonfeature () {return defaultjsonfeature;} Public String Getfeature () {return feature;} /** * Returns the corresponding string according to the attribute * * @return string */public strings Dofeature () {if (Feature.equalsignorecase (Allow_null_replaced_empty))        {return empty_string;        } else {return null_string; }}/** * Replace the string based on the attribute and return the replaced string * * @param str replaced by the target * @return the substituted string */public string dofeature (String str) {if (Feature.eq Ualsignorecase (Allow_null_replaced_empty)) {return STR.REplaceall (Regex_null, empty_string);} else {return str;}}}


Add the result type in Struts.xml:


<!--define a resulttype--><result-types><result-type name= "JSON" class= " Com.test.xiaobc.login.server.util.JsonResult "></result-type></result-types>



The above Jsonresult.java use a tool class Jsonhelps.java:


Package Com.test.xiaobc.login.server.util;import Com.alibaba.fastjson.json;import com.alibaba.fastjson.serializer.serializerfeature;/** * JSON Tool class * <p style= "Display:none" >modifyRecord</p > * @since */public abstract class Jsonhelps {/** * object serialized as JSON string * @param obj * @return */public static final Stri ng toString (Object obj) {return json.tojsonstring (obj, Serializerfeature.writemapnullvalue, Serializerfeature.disablecircularreferencedetect);}}

Finally, configure the return type of the action:


<action name= "menu" class = "loginaction" method = "Menu" ><result name= "Success" type= "JSON"/><result Name= "Error"/></action>

There are corresponding member variables in the action, and there is a Get,set method:



Then the foreground returns a string after the request:



STRUTS2 new JSON return type, automatically converts the member variable in the action to a JSON string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.