In the development of normative interfaces, general data is transmitted in JSON or XML format, rather than in the form of strings, which are directly returned to the caller of the interface, and the writing method of both formats is described below.
The following two types of data transfer methods are the output of the interface to write. The packages that need to be introduced are as follows:
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >importjava.io.PrintWriter;
Importjava.io.StringWriter;
Importjavax.servlet.http.HttpServletResponse;
importorg.dom4j.Document;
Import Org.dom4j.io.OutputFormat;
Import org.dom4j.io.xmlwriter;</span>
1. Transfer the format data of XML protocol
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/** * XML Format Data * * @param response * @param doc/publicstaticvoidoutdoctoxml (httpse
Rvletresponse response, Document doc) {//The following code please note the encoding sequence response.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Text/xml;charset=utf-8");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
PrintWriter out = null;
StringWriter writer = new StringWriter (); OutputFormat format = Outputformat.createprettyprint ();
Format.setencoding ("UTF-8");
XMLWriter XMLWriter = new XMLWriter (Writer,format);
try {out = Response.getwriter ();
Xmlwriter.write (DOC);
catch (Exception e) {e.printstacktrace ();
} out.print (Writer.tostring ());
Out.close (); }</span>
2. Format data for transmitting the JSON protocol
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/**
* JSON data Format
* *
@param response
* @param data
* @param type
* * Protectedvoidsenddata (httpservletresponse response, Object data) {
if (data!= null) {
Response.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Application/json;charset=utf-8");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
PrintWriter out = null;
try {out
= Response.getwriter ();
Out.print (data);
Out.close ();
} catch (Exception e) {
e.printstacktrace ();}}}
</span>
Please specify the source of the regularization: Blog.csdn.net/yangkai_hudong