方法一: 直接利用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 {
- em.out.println("=======================");
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setContentType( "text/xml;charset=utf-8" );
- 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>" );