以前用struts2,每次响应返回都是跳转到页面。这次的需求是要返回一个xml,查看了struts2的文档,当result的类型为xslt时,可以返回xml。但是对xslt不太熟悉,放弃了此方法。在网上搜了下,找到下面两种取巧的方法:
方法一: 直接利用ActionSuport的execute方法:
struts.xml中代码,不需要定义 result,
Action中代码,注意这里execute方法的返回为null,:
方法二:利用result类型为plaintext返回xml
struts.xml代码,
Action中代码:
方法一: 直接利用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>" );
}