|
|
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 >test</button></body></html>
可以看到页面也获得值
完 |
|