struts2.1.6 CoC + jsonplugin 快速生成json 的基础配置篇

struts2.1.6 通过XML集成 jsonplugin 生成json的文章很多,但通过CoC集成jsonplugin 的却寥寥无几,本人有幸试验成功,发布下给大家分享

CoC方式集成JsonPlugin生成json的配置步骤如下

(所有的代码都基于springside3.1.0 showcase实例测试)

配置Action

package org.springside.examples.showcase.common.web;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springside.modules.web.struts2.SimpleActionSupport;

import com.googlecode.jsonplugin.annotations.JSON;


/**
* Json 测试 Action.
*
* @author amu
*/
@SuppressWarnings("serial")
@ParentPackage("json-default")
@Namespace("/common")
public class User2Action extends SimpleActionSupport {

@Action(interceptorRefs={@InterceptorRef("paramsPrepareParamsStack"),@InterceptorRef("defaultStack")},results={@Result(type="json", name = "test")})
public String test() throws Exception {
name = "AMU: HELLO WORLD";
return "test";
}
private String name="amu";

@JSON(name="ISBN")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


NOTE
1:导入json.jar,json-lib-2.2.2-jdk15.jar,jsonplugin-0.33.jar
2:@ParentPackage一定要写json-default
3:@Result配置时,要注意的是type=“json” name一定要有名字,且方法体返回值也应该和这个配置的名字对应,否则会没有返回值
4:在需要修饰的字段上加上@JSON注释

测试下输入http://localhost:8080/showcase/common/user2!test.action
如果页面显示{"ISBN":"HELLO AMU"},或提示保存一个文件,保存下来后里面也有同样的内容就说明配置成功。

用页面测试

<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Json 示例</title>
<%@ include file="/common/meta.jsp"%>
<%@ include file="/common/taglibs.jsp"%>
<script>
function jsonTest() {
$.get("${ctx}/common/user2!test.action", {Action:"get"}, function (data, textStatus){
//返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等.
this; // 在这里this指向的是Ajax请求的选项配置信息,请参考下图
alert(data);
alert(textStatus);//请求状态:success,error等等。 当然这里捕捉不到error,因为error的时候根本不会运行该回调函数
alert(this);
});
}
</script>
</head>
<body>
<h2>Json 示例</h2>
<button onclick="jsonTest();">test</button>
</body>
</html>

可以看到页面也获得值

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值