JSON是一种轻量级的数据交换格式,大部分地方都可方便地使用。
Struts2通过利用JSON插件,也可以轻松的提供JSON数据供前台访问。
1.准备工作
本文在搭建好的struts2框架与LigerUI 插件的基础上实现的,框架的搭建不在本文的讨论范围。
以下Action用到的JSON类是alibaba的开源类库Fastjson。
相关工具包:struts2 v2.1.8、LigerUI v1.2.2、fastjson-1.1.9
2.创建Action
public class DeptAction extends ActionSupport{ private JSONObject rows; public String getDepts() throws Exception{ DeptService deptService = new DeptService(); List depts= deptService.getDepts(); HashMap<String, Object> maps = new HashMap<String, Object>(); List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); for (Dept dept :depts) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id",dept.getId()); hashMap.put("name",dept.getName()); list.add(hashMap); } maps.put("Rows", list); rows = JSONObject.parseObject(JSON.toJSONString(maps)); return SUCCESS; } public JSONObject getRows() { return rows ; } public void setRows(JSONObject rows) { this.rows = rows; } }
3.Action配置
<action name="getDepts" class="com.shelwee.domain.Dept" method="getDepts" > <result type="json" > <param name="root" >rows</param> </result> </action>
4.LigerGrid请求数据
Action创建并配置好之后,就可以在相应的页面发起请求。请求示例:
<script type="text/javascript"> $( function () { window[ 'g'] = $( "#maingrid").ligerGrid({ checkbox: true, columns: [ { display: '主键', name: 'id' , align: 'left', width: 140}, { display: '名称', name: 'name' , minWidth: 60, width: 140} ], dataAction: 'local',pageSize:10, url: '/getUsers.action' , width: '100%', height: '100%' }); $( "#pageloading").hide(); }); </script>
5.效果