java创建API,通过document生成xml返回给外部


/**
* Descriptions DoSomethingAPIサーブレット
*
* @version xxxx-xx-xx
* @author xxxx
* @since JDK1.6
*
*/
public class DoSomethingAPI extends HttpServlet {

private static final long serialVersionUID = -6628892825606366902L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// リクエストパラメータ取得
String uid = request.getParameter( "userid" );

// ユーザーステータスマップ取得
Map<String, String> userStatusMap = new HashMap<String, String>();
try {
// 応答用データ取得
userStatusMap = UserHelper.getUserStatus( uid );
} catch ( Exception e ) {
e.printStackTrace();
response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
return;
}

// 応答XML生成
String responseString = createResponseXmlString( userStatusMap );

if ( responseString == null ) {
response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
return;
}

// 応答返却
response.setContentType( "text/xml; charset=UTF-8" );
PrintWriter printWriter = response.getWriter();
printWriter.print( responseString );
}

/*-------------------------------------------------------------------------
/ メソッド名 : createResponseXmlString
/------------------------------------------------------------------------*/
/**
* アップロード通知応答用のXMLを生成し、文字列として返却します。
* @return 変換後XML文字列
* @param responseMap 応答情報Map
*/
public String createResponseXmlString( Map<String, String> responseMap ) {

String retString = null;

// XMLデータ生成
try {

Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element responseElement = document.createElement( "result" );

String nickname = responseMap.get( "nickname" );

// nickname生成
Element nicknameElement = document.createElement( "nickname" );
nicknameElement.appendChild( document.createTextNode( nickname ) );
responseElement.appendChild( nicknameElement );

Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
transformer.setOutputProperty("version","1.0");
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );

DOMSource source = new DOMSource( responseElement );
StringWriter strReturn = new StringWriter();
transformer.transform( source, new StreamResult( strReturn ) );

retString = strReturn.toString();

} catch ( Exception e ) {

e.printStackTrace();
}
return retString;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值