首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

struts2 亲切接触 json(json result type)

2012-10-13 
struts2 亲密接触 json(json result type)最近使用jquery,ajax调用后台服务非常需要一个json返回类型,网上

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;
????}转载:http://www.blogjava.net/luedipiaofeng/archive/2009/05/14/270615.html

热点排行