扩展Struts2--自定义String和XML格式的Result

struts2虽然继承了webwork优秀的MVC分离,可是有很多地方让人百思不得其解!最让人离谱的是,返回的结果集中居然没有String,xml这两种非常常用的类型。还是自己动手,丰衣足食:

 

第一种方式:使用“PlainText Result”

 

    先看官方文档对plain text结果的定义:“A result that send the content out as plain text. Usefull typically when needed to display the raw content of a JSP or Html file for example.”这是一个纯扯蛋的说法。。。貌似感觉只能返回jsp页面似的,最起码他误导了我。

 

    其实使用“PlainText Result” ,返回的结果是未进行格式和编码定义的字符串什么意思?就类似于“FreeMarker Result”  ,返回一个*.ftl格式的模板,你完全可以在*.ftl写string,那么结果就是string;也可以在里面写xml,那么结果就是xml。

 

   举例如下:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4.         "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6.     <package name="example" namespace="/example"
  7.         extends="struts-default">
  8.         <action name="outputXml"  method="outxml" class="example.OutputXml">
  9.             <result name="xmlMessage" type="plaintext"></result>
  10.         </action>
  11.     </package>
  12. </struts>

这里定义了xmlMessage为plain text结果,至于它具体是什么,看下面的Action类:

 

  1. public class OutputXml extends ActionSupport {
  2.     public void outxml() throws Exception {
  3.         HttpServletResponse response = ServletActionContext.getResponse();
  4.         response.setContentType("text/xml ");
  5.         PrintWriter pw = response.getWriter();
  6.         pw.print("<cc>cccccc</cc>");
  7.     }

    在代码中,我们显式的给response定义了ContentType。那么返回去的内容"<cc>cccccc</cc>"就会被接收方按xml进行解析。

 而如果需要返回的是String类型,那么contentType = "text/plain”。

如果进一步需要指明编码,那么contentType = "text/plain; charset=UTF-8";

 

    到这里理解“plain text的结果是未进行格式和编码定义的字符串”应该就不困难了。基于http的内容传输实际都是字符串型,类型的定义是放在response的contentType 中。

 

 

第二种方式: 直接扩展struts2的结果集StrutsResultSupport 

 

代码如下:

应该很容易懂了。。嘿嘿

  1. package commons.struts2;
  2. import java.io.PrintWriter;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.struts2.dispatcher.StrutsResultSupport;
  5. import com.opensymphony.xwork2.ActionInvocation;
  6. /**
  7.  * result type for output string in action
  8.  * 
  9.  * @author songwei,yaolei <b>Example:</b>
  10.  * 
  11.  * <pre>
  12.  * <!-- START SNIPPET: example -->
  13.  * <result name="success" type="string">
  14.  *   <param name="stringName">stringName</param>
  15.  * </result>
  16.  * <!-- END SNIPPET: example -->
  17.  * </pre>
  18.  * 
  19.  */
  20. public class StringResultType extends StrutsResultSupport {
  21.     private static final long serialVersionUID = 1L;
  22.     private String contentTypeName;
  23.     private String stringName = "";
  24.     public StringResultType() {
  25.         super();
  26.     }
  27.     public StringResultType(String location) {
  28.         super(location);
  29.     }
  30.     protected void doExecute(String finalLocation, ActionInvocation invocation)
  31.             throws Exception {
  32.         HttpServletResponse response = (HttpServletResponse) invocation
  33.                 .getInvocationContext().get(HTTP_RESPONSE);
  34.         // String contentType = (String)
  35.         // invocation.getStack().findValue(conditionalParse(contentTypeName,
  36.         // invocation));
  37.         String contentType = conditionalParse(contentTypeName, invocation);
  38.         if (contentType == null) {
  39.             contentType = "text/plain; charset=UTF-8";
  40.         }
  41.         response.setContentType(contentType);
  42.         PrintWriter out = response.getWriter();
  43.         // String result = conditionalParse(stringName, invocation);
  44.         String result = (String) invocation.getStack().findValue(stringName);
  45.         out.println(result);
  46.         out.flush();
  47.         out.close();
  48.     }
  49.     public String getContentTypeName() {
  50.         return contentTypeName;
  51.     }
  52.     public void setContentTypeName(String contentTypeName) {
  53.         this.contentTypeName = contentTypeName;
  54.     }
  55.     public String getStringName() {
  56.         return stringName;
  57.     }
  58.     public void setStringName(String stringName) {
  59.         this.stringName = stringName;
  60.     }
  61. }

 

使用的方法:

1.Action

  1. package test;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. public class MyAction extends ActionSupport{
  4.     String  result="abc";
  5.     public String ajax() {
  6.         return "ajaxResponse";
  7.     }
  8.     // getter && setter
  9.     public String getResult() {
  10.         return result;
  11.     }
  12.     public void setResult(String result) {
  13.         this.result = result;
  14.     }
  15.     
  16. }

2.定义struts.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6.     <package name="test" extends="struts-default">
  7.         <result-types>
  8.             <result-type name="string" class="test.StringResultType"></result-type>
  9.         </result-types>
  10.         
  11.         <action name="myAction" class="test.MyAction" >
  12.             <result name="ajaxResponse" type="string">
  13.                 <param name="stringName">result</param>
  14.             </result>
  15.         </action>
  16.     </package>
  17. </struts>

无非也就是将string结果集进行申明,然后给返回“ajaxResponse”的结果绑定变量名。这里定义返回Action的String  result变量,即“abc”。

 

 

第三种方式:利用Velocity ResultFreeMarker Result

类似第一种方式,这里不再重复


这里简单说一下,怎样实现一个返回JSON串的Result

方法1:

自定义的Result

[java]  view plain copy
  1. package org.ygy.demo.result;  
  2.   
  3. import java.io.PrintWriter;  
  4.   
  5. import javax.servlet.http.HttpServletResponse;  
  6.   
  7. import net.sf.json.JSONObject;  
  8. import net.sf.json.JSONSerializer;  
  9. import net.sf.json.JsonConfig;  
  10.   
  11. import org.apache.struts2.ServletActionContext;  
  12. import org.apache.struts2.dispatcher.StrutsResultSupport;  
  13.   
  14. import com.opensymphony.xwork2.ActionInvocation;  
  15.   
  16. /** 
  17.  *  
  18.  * @author yuguiyang 
  19.  * @description 返回JSON 
  20.  * @time 2013-9-4 
  21.  * @version V1.0 
  22.  */  
  23. public class JsonResult extends StrutsResultSupport {  
  24.     private static final long serialVersionUID = 2232581955223674065L;  
  25.   
  26.     private Object result;  
  27.     private JsonConfig jsonConfig;  
  28.       
  29.     public JsonResult() {}  
  30.   
  31.     public JsonResult(JsonConfig jsonConfig) {  
  32.         super();  
  33.         this.jsonConfig = jsonConfig;  
  34.     }  
  35.   
  36.     public Object getResult() {  
  37.         return result;  
  38.     }  
  39.   
  40.     public void setResult(Object result) {  
  41.         this.result = result;  
  42.     }  
  43.   
  44.     @Override  
  45.     protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {  
  46.         HttpServletResponse response = null;  
  47.         try {  
  48.             response = ServletActionContext.getResponse();  
  49.             PrintWriter printWriter = response.getWriter();  
  50.   
  51.             if (jsonConfig != null) {  
  52.                 printWriter.write(JSONObject.fromObject(result, jsonConfig).toString());  
  53.             } else {  
  54.                 printWriter.write(JSONSerializer.toJSON(result).toString());  
  55.             }  
  56.         } catch (Exception e) {  
  57.             throw new Exception("json parse error!");  
  58.         } finally {  
  59.             response.getWriter().close();  
  60.         }  
  61.   
  62.     }  
  63.   
  64. }  

这里使用json-lib来将对象转换成JSON串


Action中是这样的:

注意:这里的返回值,就是刚才自定义的JsonResult

[java]  view plain copy
  1. public JsonResult ha() {  
  2.     System.out.println("--from ha().");  
  3.       
  4.     List<String> msgs = new ArrayList<String>();  
  5.     msgs.add("one");  
  6.     msgs.add("two");  
  7.     msgs.add("three");  
  8.       
  9.     JsonResult result = new JsonResult();  
  10.     result.setResult(msgs);  
  11.       
  12.     return result;  
  13. }  

配置文件是这样的:

[html]  view plain copy
  1. <action name="ha" class="org.ygy.demo.result.HelloAction" method="ha">  
  2.     <result name="success" type="json" >/hello.jsp</result>  
  3. </action>  

PS:这里有点儿乱,明天在研究一下吧 抓狂


方法二:

[java]  view plain copy
  1. package org.ygy.demo.result;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import com.opensymphony.xwork2.ActionSupport;  
  7.   
  8. public class HelloAction extends ActionSupport {  
  9.     private static final long serialVersionUID = 6422231025855671997L;  
  10.       
  11.     private Person person;  
  12.       
  13.     public String say() {  
  14.         System.out.println("--from say().");  
  15.           
  16.           
  17.         return SUCCESS;  
  18.     }  
  19.       
  20.     public String go() {  
  21.         System.out.println("--from go().");  
  22.           
  23.         return SUCCESS;  
  24.     }  
  25.       
  26.     public JsonResult ha() {  
  27.         System.out.println("--from ha().");  
  28.           
  29.         List<String> msgs = new ArrayList<String>();  
  30.         msgs.add("one");  
  31.         msgs.add("two");  
  32.         msgs.add("three");  
  33.           
  34.         JsonResult result = new JsonResult();  
  35.         result.setResult(msgs);  
  36.           
  37.         return result;  
  38.     }  
  39.       
  40.     public String haha() {  
  41.         person = new Person(100 , "拉速度");  
  42.           
  43.         return SUCCESS;  
  44.     }  
  45.       
  46.     public Person getPerson() {  
  47.         return person;  
  48.     }  
  49.   
  50.     public void setPerson(Person person) {  
  51.         this.person = person;  
  52.     }  
  53.       
  54. }  

自定义Result:

[java]  view plain copy
  1. package org.ygy.demo.result;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.util.Map;  
  5.   
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import net.sf.json.JSONSerializer;  
  9.   
  10. import org.apache.struts2.ServletActionContext;  
  11. import org.apache.struts2.dispatcher.StrutsResultSupport;  
  12.   
  13. import com.opensymphony.xwork2.ActionContext;  
  14. import com.opensymphony.xwork2.ActionInvocation;  
  15. import com.opensymphony.xwork2.util.ValueStack;  
  16.   
  17. public class JsonResult2 extends StrutsResultSupport {  
  18.     private static final long serialVersionUID = -6528161012160891182L;  
  19.   
  20.     @Override  
  21.     protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {  
  22.         ActionContext context = invocation.getInvocationContext();  
  23.           
  24.         //通过invocation获取Action的变量   
  25.         Map<String , Object> temp = context.getContextMap();  
  26.           
  27.         Object action = invocation.getAction();  
  28.           
  29.          ValueStack stack = invocation.getStack();  
  30.          Object rootObject = stack.findValue("person");  
  31.          if(rootObject instanceof Person) {  
  32.              System.out.println("I get it.");  
  33.          }  
  34.            
  35.         //转换为JSON字符串  
  36.           
  37.         HttpServletResponse response = ServletActionContext.getResponse();  
  38.         PrintWriter out = response.getWriter();  
  39.           
  40.         out.println(JSONSerializer.toJSON(rootObject).toString());  
  41.         out.println(JSONSerializer.toJSON((Person)rootObject).toString());  
  42.           
  43.         out.flush();  
  44.         out.close();  
  45.     }  
  46.   
  47. }  

配置文件:

[html]  view plain copy
  1. <action name="haha" class="org.ygy.demo.result.HelloAction" method="haha">  
  2.     <result name="success" type="json2">/do you know me</result>  
  3. </action>  

这一次,在自定义Result时,在在值栈中找到变量Person,Struts有自己实现的JSONResult,大家可以看一下源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值