软件是对质量的不懈追求

struts2 亲密接触 json(json result type)

最近使用jquery,ajax调用后台服务非常需要一个json返回类型,网上只有一个可用的插件,叫jsonplugin 。但是测试了一下,两个版本居然都有错误,而且通过文档知道,它的使用还是相对复杂的,需要配置哪个对象需要转换,那些对象不需要。不难想象,通常我们只需要将一个对象转换成json格式,如果数据多,大不了都塞到一个对象里。
这样说起来,倒不如弃配置,转而采用规则,规定action中如果需要为ajax提供服务器端服务,必须定义一个名字叫json的成员类,类型当然是最通用的Object。然后实现一个Result,在value stack中,找到名字叫json的对象,把它序列化成json串写回客户端就ok了。

  注意:如果json的实际类型是String,这个String必须符合json语法规范。Map List之类的就无所谓,直接用就是了

  Result代码如下:

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JSONResult implements Result {
   
    private static final Log log = LogFactory.getLog(JSONResult.class);

    
public void execute(ActionInvocation invocation) throws Exception {
        ActionContext actionContext 
= invocation.getInvocationContext();
       
        HttpServletResponse response 
= (HttpServletResponse) actionContext
                .get(StrutsStatics.HTTP_RESPONSE);

        
try {
            String json;
            Object jsonObject;

            
// generate JSON
           
            ValueStack stack 
= invocation.getStack();
            jsonObject 
= stack.findValue("json");
            json 
= JSONObject.fromObject(jsonObject).toString();
           
            log.debug(json);
           
            response.setContentType(
"text/xml;charset=utf-8");
            response.getWriter().write(json);

        } 
catch (IOException exception) {
            log.error(exception.getMessage(), exception);
            
throw exception;
        }
    }

}
struts配置如下:
  <result-types>
   
<result-type name="json" class="JSONResult"/>
  
</result-types>

<action  >
    
<result name="ajax" type="json" />
</action>

action部分代码:
   

    
private Object json;
    
public Object getJson() {
        
return json;
    }

    
public void setJson(Object json) {
        
this.json = json;
    }

posted on 2009-05-14 15:20 BlakeSu 阅读(5089) 评论(2)  编辑  收藏

评论

# re: struts2 亲密接触 json(json result type) 2011-06-15 00:53

哈哈,谢谢吖!!!对帮助很大啊!!  回复  更多评论   

# re: struts2 亲密接触 json(json result type) 2014-11-24 16:19 zhaobh

很好啊  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: