日期:2014-05-16  浏览次数:20396 次

Struts2.1使用注解配置json 用jquery读取后台数据
这两天要实现用jquery读取后台数据加载到前台显示,网上找了很多教程,大同小异,最终还是摸出来的.感谢互联网


我使用的是springside3.2,struts版本是2.18



一,首先是包的问题

开始根据网上下载了google的jsonplugin包,运行出错java.lang.NoClassDefFoundError:com/opensymphony/xwork2/util/TextUtils,到apache网站上发现从struts2.17开始就不再使用google的那个jsonplugin包了,不过官网没找到下载的链接,搜索下载了struts2-json-plugin-2.1.8.1.jar,json-lib-2.2.3-jdk15.jar,加载到项目后正常,除外lib还应包含commons-beanutils.jar,commons-collections.jar,commons-logging.jar,commons-lang.jar



二,Struts2中Action的配置

由于使用注解方式配置action,不用配置struts.xml.由于action类的父java包需要继承json-default,返回json数据,所以再新建一个专门返回json数据的action类,


//ParentPackage注解用来定义具体action类的父XWork包或java包,一定要配置

@ParentPackage("json-default")

//命名空间

@Namespace("/management")

//此action类所有方法返回json对象,必须配置

@Results(

{@Result(type="json")})


publicclass JsonAction extends ActionSupport{


//此处通过spring注入type的管理类,用来执行查询数据库动作

@Autowired

privateTypeManager      typeManager;


//返回的LIST数据,type是一个普通的javabean对象,这里只有id跟name属性

//返回success,json-lib会将所有java属性转换成一个的json数组,也可以直接在方法中返回JSONResult

private List<Type> typeList = new ArrayList<Type>();


……

//此处省略typeList的get和set方法,必须



publicStringfileType(){



typeList=typeManager.getAllType();



return SUCCESS;


}   }


//如果使用struts.xml,则配置如下


<struts>

<packagename="management" extends="json-default">

<actionname="Json" class="com.JsonAction">

<resulttype="json"/>

</action>

</package>

</struts>



三,jquery查询

也可以使用$.ajax()方法,这里使用getJSON()方法,只配置请求路径跟处理结果的方法,data值返回的是页面所有的属性组成的一个数组,可使用data.属性名取得相应对象,若程序无出错提示,但获取不到数据,可能是返回结果的结构读取不正确,可直接在地址栏上输入完整的请求路径,可以将返回的结果打开或下载,用记事本打开即可看到返回的json数据,再根据结构读取.从firebug控制台看响应的结果则更方便


$(document)

.ready(

function(){


//${ctx}是目录的路径

$.getJSON("${ctx}/management/json!fileType.action",function(data){



    $.each(data.typeList,function(i,item){


$("#typeId").append("<optionvalue="+item.id+">"+item.name+"</option>");


});

});


1 楼 tianzhijie11 2010-12-09  
代码不是一般的乱,你的方法好像不行。
@Results(

{@Result(type="json")}) 这里就通不过