Struts2 返回 xml 信息

Struts2 返回 xml 信息

id="iframeu1252119_0" src="http://pos.baidu.com/jcqm?rdid=1252119&dc=2&di=u1252119&dri=0&dis=0&dai=1&ps=387x516&dcb=BAIDU_SSP_define&dtm=HTML_POST&dvi=0.0&dci=-1&dpt=none&tsr=0&tpr=1470188734905&ti=Struts2%20%E8%BF%94%E5%9B%9E%20xml%20%E4%BF%A1%E6%81%AF%20-%20%E4%B8%AD%E8%B5%A2%E7%BD%91&ari=2&dbv=2&drs=1&pcs=1879x887&pss=1879x538&cfv=0&cpl=23&chi=1&cce=true&cec=UTF-8&tlm=1470188734&rw=887&ltu=http%3A%2F%2Fit.chinawin.net%2Fsoftwaredev%2Farticle-fd55.html&ltr=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DpJneV_23S8ecfbezVslynaP0jBqAXcyjVusrZEX9yEV5IYltHqlDRVUwlueonVCmgyRv5-Dv9m-GiOLpqMq_1_%26wd%3D%26eqid%3Dc22ebf9a0010070a0000000657a14ca1&ecd=1&psr=1920x1080&par=1920x1040&pis=-1x-1&ccd=24&cja=true&cmi=46&col=zh-CN&cdo=-1&tcn=1470188735&qn=333eea10e497b1db&tt=1470188734871.37.87.90" width="580" height="90" align="center,center" vspace="0" hspace="0" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="border-width: 0px; border-style: initial; vertical-align: bottom; margin: 0px;">
以前用 struts2,每次响应返回都是跳转到页面。这次的需求是要返回一个xml,查看了struts2的文档,当result的类型为xslt时,可以返回xml。但是对xslt不太熟悉,放弃了此方法。在网上搜了下,找到下面两种取巧的方法:

  
     方法一: 直接利用ActionSuport的execute方法:

     

        struts.xml中代码,不需要定义 result,

        
<action name="OutxmlExecute"  class="com.OutxmlExecuteAction" >
</action>

       

       Action中代码,注意这里execute方法的返回为null,:

         
public String execute() throws IOException{
String outPut = "<persons>";
outPut += "<person1><name>hanyoud</name><age>25</age></person1>";
outPut += "<person2><name>张三</name><age>18</age></person2>";
outPut += "<person3><name>李四</name><age>20</age></person3>";
outPut += "</persons>";
//转换编码 否则汉字显示为乱码
outPut = new String(outPut.getBytes("UTF-8"),"ISO-8859-1");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/xml ");
PrintWriter pw = response.getWriter();
pw.print(outPut);
System.out.println("-------------------------------");
return null;
}
    方法二:利用result类型为plaintext返回xml
     struts.xml代码,

      
<action name="Outxml" method="outxml" class="com.OutxmlAction" >
<result name="xmlMessage" type="plaintext"></result>
</action>
     Action中代码:

public   void  outxml() throws IOException   { 
System.out.println("=======================");
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType( "text/xml " );
PrintWriter pw = response.getWriter();
pw.print( "<persons>" );
pw.print( "<person1><name>hanyoud</name><age>25</age></person1>" );
pw.print( "<person2><name>ss</name><age>18</age></person2>" );
pw.print( "</persons>" );
}
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值