Struts2 返回 xml 格式数据

来源:互联网 发布:三星note5绘图软件 编辑:程序博客网 时间:2024/06/05 02:11

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

  

        struts.xml中代码,不需要定义 result, 
        
Java代码  收藏代码
  1. <action name="OutxmlExecute"  class="com.OutxmlExecuteAction" >  
  2.          
  3. </action>  
  4.   
  5.    

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

Java代码  收藏代码
  1. public String execute() throws IOException{  
  2.         String outPut = "<persons>";  
  3.         outPut += "<person1><name>hanyoud</name><age>25</age></person1>";  
  4.         outPut += "<person2><name>张三</name><age>18</age></person2>";  
  5.         outPut += "<person3><name>李四</name><age>20</age></person3>";  
  6.         outPut += "</persons>";  
  7.           
  8.         //转换编码 否则汉字显示为乱码  
  9.         outPut = new String(outPut.getBytes("UTF-8"),"ISO-8859-1");  
  10.           
  11.           
  12.           
  13.         HttpServletResponse response = ServletActionContext.getResponse();  
  14.         response.setContentType("text/xml ");  
  15.         PrintWriter pw = response.getWriter();  
  16.         pw.print(outPut);  
  17.         System.out.println("-------------------------------");  
  18.         return null;  
  19.     }  
  20.   
  21.   
  22.           

    方法二:利用result类型为plaintext返回xml 

     struts.xml代码, 
      
Java代码  收藏代码
  1. <action name="Outxml" method="outxml" class="com.OutxmlAction" >  
  2.                <result name="xmlMessage" type="plaintext"></result>   
  3.                           
  4.        </action>   
  5.         


     Action中代码: 
Java代码  收藏代码
  1. public   void  outxml() throws IOException   {   
  2. em.out.println("=======================");  
  3.   HttpServletResponse response = ServletActionContext.getResponse();   
  4.   response.setContentType( "text/xml;charset=utf-8" );   
  5.   PrintWriter pw = response.getWriter();   
  6.   pw.print( "<persons>" );   
  7.   pw.print( "<person1><name>hanyoud</name><age>25</age></person1>" );   
  8.   pw.print( "<person2><name>ss</name><age>18</age></person2>" );   
  9.   pw.print( "</persons>" );   
0 0
原创粉丝点击