Java background returns JSON data to foreground __JS

Source: Internet
Author: User
Tags dateformat getmessage tojson log4j

First step: Create a new Jsonbinder.java class with the following code:

Import java.io.IOException;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.HashMap;
Import Java.util.Map;
Import Org.apache.log4j.LogManager;
Import Org.apache.log4j.Logger;
Import Org.codehaus.jackson.map.DeserializationConfig;
Import Org.codehaus.jackson.map.ObjectMapper;
Import org.codehaus.jackson.map.annotate.JsonSerialize;

Import Org.springframework.util.StringUtils;

public class Jsonbinder {private static Logger Logger = Logmanager.getlogger (Jsonbinder.class);

Private Objectmapper Mapper; 

@SuppressWarnings ("deprecation") private Jsonbinder (Jsonserialize.inclusion inclusion) {mapper = new objectmapper ();

Sets the properties that the output contains Mapper.getserializationconfig (). Setserializationinclusion (inclusion); Setting input ignores Properties Mapper.getdeserializationconfig () that exist in the JSON string and the Java object actually does not. Set (DeserializationConfig.Feature.FAIL_ON_
Unknown_properties,false);
The public Jsonbinder () {}/** * Creates a binder that outputs all properties to the JSON string. */public static Jsonbinder Buildnormalbinder () {return new JSonbinder (JsonSerialize.Inclusion.ALWAYS);
/** * Creates a binder that outputs only non-null attributes to the JSON string.

*/public static Jsonbinder Buildnonnullbinder () {return new Jsonbinder (JsonSerialize.Inclusion.NON_NULL);}
/** * Creates a binder that outputs only the properties that are changed by the initial value to the JSON string.

*/public static Jsonbinder Buildnondefaultbinder () {return new Jsonbinder (JsonSerialize.Inclusion.NON_DEFAULT);}
/** * Creates a binder that outputs only the properties that are changed by the initial value to the JSON string.

*/public static Jsonbinder Buildnonemptybinder () {return new Jsonbinder (JsonSerialize.Inclusion.NON_EMPTY);}
/** * Returns NULL if the JSON string is null or a "null" string.
* If the JSON string is "[]", returns an empty collection. * * If you want to read the collection such as List/map, and not list<string> this simple type, use the following statement: * list<mybean> beanlist = Binder.getmapper (). ReadValue (
ListString, New Typereference<list<mybean>> () {}); */Public <T> T Fromjson (String jsonstring, class<t> clazz) {try {return mapper.readvalue (jsonstring, Clazz)
; 
catch (IOException e) {Logger.warn ("Parse JSON string error:" + jsonstring, E);
return null;
}/** * returns "NULL" if the object is null. * If the collection is an empty collection, returns "[]". */Public String Tojson (object) {try {return mapper.writevalueasstring (object);} catch (IOException e) {Logger
. Warn ("Write to JSON string error:" + object, E);
return null;
/** * Sets the format pattern for the conversion date type, if you do not set the default print timestamp number of milliseconds. */public void Setdateformat (String pattern) {if (stringutils.hastext) {DateFormat df = new SimpleDateFormat (PA
Ttern);
Mapper.getserializationconfig (). Withdateformat (DF);
Mapper.getdeserializationconfig (). Withdateformat (DF);
}/** * Remove mapper for further setup or use other serialization APIs. * * Public objectmapper Getmapper () {return mapper;}/** * Character conversion Map * @param line * @return/public map<string, OBJEC
T> Stringmap (String line) {string Linestring=line.replace ("{", "");
String linstring=linestring.replace ("}", "");
Map<string,object> retmap=new hashmap<string, object> ();
String [] Linestrings=linstring.split (",");
for (int i = 0; i < linestrings.length i++) {String Lenstring=linestrings[i].trim (); String Lidd[]=lenstring.split ("=");
Retmap.put (Lidd[0].trim (), Lidd[1].trim ());
return retmap; }

}

Step Two: Create a new Jsonreturnmodel.java class with the following code:

Import java.io.Serializable;

public class Jsonreturnmodel implements Serializable {
private static final long Serialversionuid =-6705263054881844 917L;
Private Boolean success;//whether successful
private int code;
Private String msg; Returns the message public

int GetCode () {return
code;
}

public void Setcode (int code) {
this.code = code;
}

Public Jsonreturnmodel () {
} public

Jsonreturnmodel (boolean success, int code, String msg) {
this.success = success;
This.code = code;
this.msg = msg;
}

Public Jsonreturnmodel (Boolean success, String msg) {
this.success = success;
this.msg = msg;
}

public Boolean getsuccess () {return
success;
}

public void Setsuccess (Boolean success) {
this.success = success;
}

Public String getmsg () {return
msg;
}

public void Setmsg (String msg) {
this.msg = msg;
}
}

Step Three: Test

Import java.io.UnsupportedEncodingException;
Import Com.sqzw.sms.util.JsonBinder;
Import Com.sqzw.sms.util.JsonReturnModel;
public class Test {public
static void Main (string[] args) throws Unsupportedencodingexception {
Jsonreturnmodel Jm=new Jsonreturnmodel (true,0, "Connect the server successfully");
Jsonbinder Jsonbinder=jsonbinder.buildnonnullbinder ();
String Result=jsonbinder.tojson (JM);
SYSTEM.OUT.PRINTLN (result);
}

The results of the operation are as follows:

{"Success": True, "code": 0, "MSG": "Connect server Succeeded"}

Step Fourth: Create a new Smssendmessageaction.java class to inherit Actionsupport, code as follows:

Import java.io.IOException;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.log4j.LogManager;
Import Org.apache.log4j.Logger;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.sqzw.sms.util.Common;
Import Com.sqzw.sms.util.JsonReturnModel; public class Smssendmessageaction extends actionsupport{private static final long Serialversionuid = 1087655523102850222
L
Private Logger Logger=logmanager.getlogger (Smssendmessageaction.class); 
Private HttpServletResponse response = null; /** * @method: Checkservice * @desc Verify that the connection server is successful * @since 2012-07-16 * @author FX/public void Checkservice () {Response=se
Rvletactioncontext.getresponse ();
Response.setcharacterencoding ("Utf-8");

try{response.getwriter (). Print (Common.returnjsonresult (new Jsonreturnmodel (true,0, "Connection server succeeded")); }catch (Exception ex) {try {response.getwriter (). Print (Common.returnjsonresult new Jsonreturnmodel (False,-1, "
Connection Server failed "))); catch (IOException E{//TODO auto-generated catch block Logger.error ("Connection Server failed::" +e.getmessage ());} logger.error ("Connection Server failed::" +

Ex.getmessage ()); }finally{try {response.getwriter (). Close ();} catch (Exception e) {logger.error ("Smssendmessageaction Class |

Checkservice () off IO error:: "+e.getmessage ()); }
}
}
}

The results of the operation are as follows:

Http://localhost:8080/sms/checkServiceAction.action

Related Article

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.