jqGrid列表渲染使用

最近基于之前jqgrid+struts的基础上,做了一个jqgrid+spring的例子,大家请上眼。

零:

工程项目图:


一 View


   
   
    
    
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <%@ include file="/resources/common/include/header.jsp" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  8. <title>jqgrid demo </title>
  9. <!-- JQuery CSS -->
  10. <link rel="stylesheet" href="${basePath}/resources/plugin/jquery-ui-themes-1.8.14/themes/redmond/jquery-ui.css" type="text/css" />
  11. <!-- jqGrid CSS -->
  12. <link rel="stylesheet" href="${basePath}/resources/plugin/jqGrid-4.5.4/css/ui.jqgrid.css" type="text/css" />
  13. <!-- The actual JQuery code -->
  14. <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js" > </script>
  15. <!-- The JQuery UI code -->
  16. <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"> </script>
  17. <!-- The jqGrid language file code-->
  18. <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/i18n/grid.locale-cn.js"> </script>
  19. <!-- The atual jqGrid code -->
  20. <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/jquery.jqGrid.src.js"> </script>
  21. <script type="text/javascript">
  22. $( function( ){
  23. $( "#gridTable"). jqGrid({
  24. url: "${basePath}/itCrud/list",
  25. datatype: "json",
  26. mtype : "post",
  27. height: 250,
  28. colNames:[ 'Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
  29. colModel:[
  30. { name: 'id', index: 'id', width: 55, editable: true, editoptions:{ readonly: true}, sorttype: 'int'},
  31. { name: 'invdate', index: 'invdate', width: 90, editable: true},
  32. { name: 'name', index: 'name asc, invdate', width: 100, editable: true},
  33. { name: 'amount', index: 'amount', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  34. { name: 'tax', index: 'tax', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  35. { name: 'total', index: 'total', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  36. { name: 'note', index: 'note', width: 150, sortable: false, editable: true}
  37. ],
  38. sortname: 'id',
  39. sortorder: 'asc',
  40. /*editurl: 'server.php', */
  41. viewrecords: true,
  42. rowNum: 10,
  43. rowList:[ 10, 20, 30],
  44. prmNames : {
  45. search : "search"
  46. },
  47. jsonReader : {
  48. root : "rows",
  49. page: "page",
  50. total: "total",
  51. records : "records",
  52. repeatitems : false
  53. },
  54. pager: "#gridPager",
  55. caption: "jqgrid CRUD demo",
  56. hidegrid : false
  57. });
  58. $( '#gridTable'). jqGrid( 'navGrid', '#gridPager',{
  59. refresh: true,
  60. edit: true,
  61. add: true,
  62. del: true,
  63. search: false,
  64. addfunc:openDialog4Adding,
  65. editfunc:openDialog4Updating,
  66. delfunc:openDialog4Deleting
  67. });
  68. //配置对话框
  69. $( "#consoleDlg"). dialog({
  70. autoOpen: false,
  71. modal: true //设置对话框为模态对话框
  72. });
  73. });
  74. var openDialog4Adding = function( ) {
  75. var consoleDlg = $( "#consoleDlg");
  76. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  77. consoleDlg. find( "input"). removeAttr( "disabled"). val( "");
  78. // dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  79. // dialogButtonPanel.find("button:contains('新增')").show();
  80. consoleDlg. dialog({
  81. title: "新增",
  82. resizable: false,
  83. width: 480,
  84. buttons:{
  85. "取消": function( ){
  86. $( "#consoleDlg"). dialog( "close");
  87. },
  88. "新增":addItem
  89. }
  90. });
  91. consoleDlg. dialog( "open");
  92. };
  93. var openDialog4Updating = function( ) {
  94. var consoleDlg = $( "#consoleDlg");
  95. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  96. consoleDlg. find( "input"). removeAttr( "disabled");
  97. /* dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  98. dialogButtonPanel.find("button:contains('修改')").show(); */
  99. consoleDlg. dialog({
  100. title: "修改",
  101. resizable: false,
  102. width: 480,
  103. buttons:{
  104. "取消": function( ){
  105. $( "#consoleDlg"). dialog( "close");
  106. },
  107. "修改":editItem
  108. }
  109. });
  110. loadSelectedRowData();
  111. consoleDlg. dialog( "open");
  112. };
  113. var openDialog4Deleting = function( ) {
  114. var consoleDlg = $( "#consoleDlg");
  115. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  116. consoleDlg. find( "input"). attr( "disabled", true);
  117. /*
  118. dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  119. dialogButtonPanel.find("button:contains('删除')").show();
  120. consoleDlg.dialog("option", "title", "delete record");
  121. */
  122. consoleDlg. dialog({
  123. title: "删除",
  124. resizable: false,
  125. width: 480,
  126. buttons:{
  127. "取消": function( ){
  128. $( "#consoleDlg"). dialog( "close");
  129. },
  130. "删除":deleteItem
  131. }
  132. });
  133. loadSelectedRowData();
  134. consoleDlg. dialog( "open");
  135. };
  136. var loadSelectedRowData = function( ){
  137. //2016-03-18 当前选中的行
  138. var selectedRowId = $( "#gridTable"). jqGrid( "getGridParam", "selrow");
  139. //获得当前行各项属性
  140. var rowData = $( "#gridTable"). jqGrid( "getRowData",selectedRowId);
  141. if (!selectedRowId) {
  142. alert( "请先选择需要编辑的行!");
  143. return false;
  144. } else {
  145. var consoleDlg = $( "#consoleDlg");
  146. consoleDlg. find( "#selectId"). val(rowData. id);
  147. consoleDlg. find( "#invdate"). val(rowData. invdate);
  148. consoleDlg. find( "#name"). val(rowData. name);
  149. consoleDlg. find( "#amount"). val(rowData. amount);
  150. consoleDlg. find( "#tax"). val(rowData. tax);
  151. consoleDlg. find( "#total"). val(rowData. total);
  152. consoleDlg. find( "#note"). val(rowData. note);
  153. }
  154. };
  155. var openDialog4Deleting = function( ) {
  156. var consoleDlg = $( "#consoleDlg");
  157. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  158. consoleDlg. find( "input"). attr( "disabled", true);
  159. /*
  160. dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  161. dialogButtonPanel.find("button:contains('删除')").show();
  162. consoleDlg.dialog("option", "title", "delete record");
  163. */
  164. consoleDlg. dialog({
  165. title: "删除",
  166. resizable: false,
  167. width: 480,
  168. buttons:{
  169. "取消": function( ){
  170. $( "#consoleDlg"). dialog( "close");
  171. },
  172. "删除":deleteItem
  173. }
  174. });
  175. loadSelectedRowData();
  176. consoleDlg. dialog( "open");
  177. };
  178. var addItem = function( ){
  179. var consoleDlg = $( "#consoleDlg");
  180. var invdate = $. trim(consoleDlg. find( "#invdate"). val());
  181. var name = $. trim(consoleDlg. find( "#name"). val());
  182. var amount = $. trim(consoleDlg. find( "#amount"). val());
  183. var tax = $. trim(consoleDlg. find( "#tax"). val());
  184. var total = $. trim(consoleDlg. find( "#total"). val());
  185. var note = $. trim(consoleDlg. find( "#note"). val());
  186. var params = {
  187. "invdate" : invdate,
  188. "name" : name,
  189. "amount" : amount,
  190. "tax" : tax,
  191. "total" : total,
  192. "note" : note
  193. };
  194. $. ajax({
  195. url: "${basePath}/itCrud/add",
  196. data : params,
  197. dataType : "json",
  198. cache : false,
  199. success : function( response, textStatus) {
  200. /* alert("id123-->" + response.id + "; message-->" + response.message); */
  201. if (response. message == true) {
  202. var dataRow = {
  203. id : response. id, //从server端获得系统分配的id
  204. invdate : invdate,
  205. name : name,
  206. amount : amount,
  207. tax : tax,
  208. total : total,
  209. note : note
  210. };
  211. /*
  212. var srcrowid = $("#gridTable").jqGrid("getGridParam",
  213. "selrow");
  214. */
  215. $( "#gridTable"). jqGrid( "addRowData",
  216. response. id, dataRow, "last"); //将新行插入到末尾
  217. consoleDlg. dialog( "close");
  218. alert( "添加成功!");
  219. } else{
  220. alert( "添加失败!");
  221. }
  222. },
  223. error : function( textStatus, e) {
  224. alert( "系统ajax交互错误: " + textStatus);
  225. }
  226. });
  227. };
  228. var editItem = function( ){
  229. var consoleDlg = $( "#consoleDlg");
  230. var id = $. trim(consoleDlg. find( "#selectId"). val());
  231. var tempInvdate = $. trim(consoleDlg. find( "#invdate"). val());
  232. var invdate = tempInvdate. substring( 0, 10);
  233. var name = $. trim(consoleDlg. find( "#name"). val());
  234. var amount = $. trim(consoleDlg. find( "#amount"). val());
  235. var tax = $. trim(consoleDlg. find( "#tax"). val());
  236. var total = $. trim(consoleDlg. find( "#total"). val());
  237. var note = $. trim(consoleDlg. find( "#note"). val());
  238. var params = {
  239. "id" : id,
  240. "invdate" : invdate,
  241. "name" : name,
  242. "amount" : amount,
  243. "tax" : tax,
  244. "total" : total,
  245. "note" : note
  246. };
  247. $. ajax({
  248. url: "${basePath}/itCrud/edit",
  249. data : params,
  250. dataType : "json",
  251. cache : false,
  252. success : function( response, textStatus) {
  253. // alert("id-->" + response.id + "; message-->" + response.message);
  254. if (response. message == true) {
  255. var dataRow = {
  256. selectId : id,
  257. invdate : invdate,
  258. name : name,
  259. amount : amount,
  260. tax : tax,
  261. total : total,
  262. note : note
  263. };
  264. /*
  265. var srcrowid = $("#gridTable").jqGrid("getGridParam",
  266. "selrow");
  267. */
  268. //将表格中对应记录更新一下
  269. $( "#gridTable"). jqGrid( "setRowData", id, dataRow);
  270. consoleDlg. dialog( "close");
  271. alert( "修改成功!");
  272. } else{
  273. alert( "修改失败!");
  274. }
  275. },
  276. error : function( textStatus, e) {
  277. alert( "系统ajax交互错误: " + textStatus);
  278. }
  279. });
  280. }
  281. var deleteItem = function( ){
  282. var consoleDlg = $( "#consoleDlg");
  283. var id = $. trim(consoleDlg. find( "#selectId"). val());
  284. var tempInvdate = $. trim(consoleDlg. find( "#invdate"). val());
  285. var invdate = tempInvdate. substring( 0, 10);
  286. var name = $. trim(consoleDlg. find( "#name"). val());
  287. var amount = $. trim(consoleDlg. find( "#amount"). val());
  288. var tax = $. trim(consoleDlg. find( "#tax"). val());
  289. var total = $. trim(consoleDlg. find( "#total"). val());
  290. var note = $. trim(consoleDlg. find( "#note"). val());
  291. var params = {
  292. "id" : id,
  293. "invdate" : invdate,
  294. "name" : name,
  295. "amount" : amount,
  296. "tax" : tax,
  297. "total" : total,
  298. "note" : note
  299. };
  300. $. ajax({
  301. url: "${basePath}/itCrud/delete",
  302. data : params,
  303. dataType : "json",
  304. cache : false,
  305. success : function( response, textStatus) {
  306. // alert("id-->" + response.id + "; message-->" + response.message);
  307. if (response. message == true) {
  308. $( "#gridTable"). jqGrid( "delRowData", id);
  309. consoleDlg. dialog( "close");
  310. alert( "删除成功!");
  311. } else{
  312. alert( "删除失败!");
  313. }
  314. },
  315. error : function( textStatus, e) {
  316. alert( "系统ajax交互错误: " + textStatus);
  317. }
  318. });
  319. }
  320. </script>
  321. </head>
  322. <body>
  323. <table id="gridTable"> </table>
  324. <div id="gridPager"> </div>
  325. <div id="consoleDlg" style="display:none">
  326. <form id="consoleForm">
  327. <input type="hidden" id="selectId"/>
  328. <table class="formTable">
  329. <tr>
  330. <th>Date </th>
  331. <td> <input type="text" class="textField" id="invdate" name="invdate" />
  332. </td>
  333. </tr>
  334. <tr>
  335. <th>Client </th>
  336. <td> <input type="text" class="textField" id="name" name="name" />
  337. </td>
  338. </tr>
  339. <tr>
  340. <th>Amount </th>
  341. <td> <input type="text" class="textField" id="amount" name="amount" />
  342. </td>
  343. </tr>
  344. <tr>
  345. <th>Tax </th>
  346. <td> <input type="text" class="textField" id="tax" name="tax" />
  347. </td>
  348. </tr>
  349. <tr>
  350. <th>Total </th>
  351. <td> <input type="text" class="textField" id="total" name="total" />
  352. </td>
  353. </tr>
  354. <tr>
  355. <th>Notes </th>
  356. <td> <input type="text" class="textField" id="note" name="note" />
  357. </td>
  358. </tr>
  359. </table>
  360. </form>
  361. </div>
  362. </body>
  363. </html>


二 Model


   
   
    
    
  1. package com.yangw.demo.pojo;
  2. import com.yangw.demo.base.BasePojo;
  3. public class Item extends BasePojo {
  4. private static final long serialVersionUID = 1L;
  5. private int id;
  6. private String invdate;
  7. private String name;
  8. private double amount;
  9. private double tax;
  10. private double total;
  11. private String note;
  12. public int getId () {
  13. return id;
  14. }
  15. public void setId (int id) {
  16. this.id = id;
  17. }
  18. public String getInvdate () {
  19. return invdate;
  20. }
  21. public void setInvdate (String invdate) {
  22. this.invdate = invdate;
  23. }
  24. public String getName () {
  25. return name;
  26. }
  27. public void setName (String name) {
  28. this.name = name;
  29. }
  30. public double getAmount () {
  31. return amount;
  32. }
  33. public void setAmount (double amount) {
  34. this.amount = amount;
  35. }
  36. public double getTax () {
  37. return tax;
  38. }
  39. public void setTax (double tax) {
  40. this.tax = tax;
  41. }
  42. public double getTotal () {
  43. return total;
  44. }
  45. public void setTotal (double total) {
  46. this.total = total;
  47. }
  48. public String getNote () {
  49. return note;
  50. }
  51. public void setNote (String note) {
  52. this.note = note;
  53. }
  54. }


三 Action

1 MediatorController


   
   
    
    
  1. @Controller
  2. @RequestMapping("/main")
  3. public class MediatorController {
  4. @RequestMapping(value = "/items", method = RequestMethod.GET)
  5. public String getItemPage (){
  6. return "listView";
  7. }
  8. }


2 JqDemoController


   
   
    
    
  1. @Controller
  2. @RequestMapping(value={"/itCrud"})
  3. public class JqDemoController extends BaseController {
  4. @Autowired
  5. private IItemService<Item, Integer> itemService;
  6. private List<Item> dataList;
  7. @RequestMapping(value={"/list"})
  8. public @ResponseBody DataResponse<Item> showList (
  9. Item item,
  10. @RequestParam(defaultValue="1",value="page") String page,
  11. @RequestParam(defaultValue="10",value="rows") String rows
  12. ){
  13. int records; //总记录数
  14. int totalPages; //总页数
  15. int pageSize = StringUtils.isEmpty(rows) ? 10 : Integer.valueOf(rows); //每页显示记录数
  16. int currPage = StringUtils.isEmpty(page) ? 1 : Integer.valueOf(page); //当前页码
  17. DataResponse<Item> response = new DataResponse<Item>();
  18. try {
  19. records = itemService.getEntityCount(item);
  20. totalPages = (records + pageSize - 1) / pageSize;
  21. int start = pageSize * (currPage - 1) + 1;
  22. start = (start < 0) ? 0 : start;
  23. int stop = currPage * pageSize;
  24. item.setStart(start);
  25. item.setStop(stop);
  26. dataList = itemService.searchEntityList(item);
  27. response.setRecords(String.valueOf(records));
  28. response.setTotal(String.valueOf(totalPages));
  29. response.setPage(String.valueOf(currPage));
  30. response.setRows(dataList);
  31. } catch (Exception e) {
  32. // TODO Auto-generated catch block
  33. e.printStackTrace();
  34. }
  35. return response;
  36. }
  37. @RequestMapping(value={"/add"})
  38. public @ResponseBody ResultResponse add (Item item) throws Exception{
  39. ResultResponse response = new ResultResponse();
  40. try {
  41. System.out.println(item);
  42. itemService.insertEntity(item);
  43. response.setId( 100);
  44. response.setMessage( true);
  45. } catch (Exception e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. response.setMessage( false);
  49. throw e;
  50. }
  51. return response;
  52. }
  53. @RequestMapping(value={"/edit"})
  54. public @ResponseBody ResultResponse edit (Item item) throws Exception{
  55. ResultResponse response = new ResultResponse();
  56. try {
  57. System.out.println(item);
  58. itemService.updateEntity(item);
  59. response.setMessage( true);
  60. } catch (Exception e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. response.setMessage( false);
  64. throw e;
  65. }
  66. return response;
  67. }
  68. @RequestMapping(value={"/delete"})
  69. public @ResponseBody ResultResponse delete (Item item) throws Exception{
  70. ResultResponse response = new ResultResponse();
  71. try {
  72. System.out.println(item);
  73. itemService.deleteEntity(item);
  74. response.setMessage( true);
  75. } catch (Exception e) {
  76. // TODO Auto-generated catch block
  77. e.printStackTrace();
  78. response.setMessage( false);
  79. throw e;
  80. }
  81. return response;
  82. }
  83. public List<Item> getDataList () {
  84. return dataList;
  85. }
  86. public void setDataList (List<Item> dataList) {
  87. this.dataList = dataList;
  88. }
  89. }



四 Service

1 BaseService


   
   
    
    
  1. public interface BaseService<Entity extends Serializable,Query extends Object> {
  2. /**
  3. * 添加 实体
  4. * sqlKey insertEntity
  5. * @param entity
  6. * @return
  7. * @throws Exception
  8. */
  9. public Query insertEntity (Entity entity) throws Exception;
  10. /**
  11. * 修改 实体
  12. * sqlKey updateEntity
  13. * @param entity
  14. * @return
  15. * @throws Exception
  16. */
  17. public int updateEntity (Entity entity) throws Exception;
  18. /**
  19. * 删除 实体
  20. * sqlKey deleteEntityById
  21. * @param entity
  22. * @return
  23. * @throws Exception
  24. */
  25. public int deleteEntity (Entity entity) throws Exception;
  26. /**
  27. * 根据实体参数查找单个数据
  28. * sqlKey searchEntity
  29. * @param sqlMap
  30. * @param query
  31. * @return
  32. * @throws Exception
  33. */
  34. public Entity searchEntity (Entity entity) throws Exception;
  35. /**
  36. * 查询 实体列表
  37. * sqlKey searchEntityList
  38. * @param query
  39. * @return
  40. * @throws Exception
  41. */
  42. public List<Entity> searchEntityList (Entity entity) throws Exception;
  43. /**
  44. * 查询总数
  45. * @param sqlMap
  46. * @param query
  47. * @throws Exception
  48. */
  49. public int getEntityCount (Entity entity) throws Exception;
  50. }

2 ItemServiceImpl


   
   
    
    
  1. @Service
  2. public class ItemServiceImpl extends BaseServiceSupport<Item, Integer> implements IItemService<Item, Integer> {
  3. @Resource(name="itemDao")
  4. private ItemDao itemDao;
  5. }

五 Dao层

1 BaseDao


   
   
    
    
  1. public interface BaseDao<Entity extends Serializable, Query extends Object> {
  2. /**
  3. * 添加 实体
  4. * @param entity
  5. * @return
  6. * @throws SQLException
  7. */
  8. public Query insertEntity (Entity entity) throws SQLException;
  9. /**
  10. * 修改 实体
  11. * @param entity
  12. * @return
  13. * @throws SQLException
  14. */
  15. public int updateEntity (Entity entity) throws SQLException;
  16. /**
  17. * 删除 实体
  18. * @param entity
  19. * @return
  20. * @throws SQLException
  21. */
  22. public int deleteEntity (Entity entity) throws SQLException;
  23. /**
  24. * 根据实体参数查找单个数据
  25. * @param sqlMap
  26. * @param query
  27. * @return
  28. * @throws SQLException
  29. */
  30. public Entity searchEntity (Entity entity) throws SQLException;
  31. /**
  32. * 查询 实体列表
  33. * @param query
  34. * @return
  35. * @throws SQLException
  36. */
  37. public List<Entity> searchEntityList (Entity entity) throws SQLException;
  38. /**
  39. * 查询总数
  40. * @param sqlMap
  41. * @param query
  42. * @throws SQLException
  43. */
  44. public int getEntityCount (Entity entity) throws SQLException;
  45. }


六 json

1 DataResponse


   
   
    
    
  1. public class DataResponse<T> {
  2. private String page;
  3. private String total;
  4. private String records;
  5. private List<T> rows;
  6. private Map<String, Object> userdata;
  7. public String getPage () {
  8. return page;
  9. }
  10. public void setPage (String page) {
  11. this.page = page;
  12. }
  13. public String getTotal () {
  14. return total;
  15. }
  16. public void setTotal (String total) {
  17. this.total = total;
  18. }
  19. public String getRecords () {
  20. return records;
  21. }
  22. public void setRecords (String records) {
  23. this.records = records;
  24. }
  25. public List<T> getRows () {
  26. return rows;
  27. }
  28. public void setRows (List<T> rows) {
  29. this.rows = rows;
  30. }
  31. public Map<String, Object> getUserdata () {
  32. return userdata;
  33. }
  34. public void setUserdata (Map<String, Object> userdata) {
  35. this.userdata = userdata;
  36. }
  37. }


2 ResultResponse


   
   
    
    
  1. public class ResultResponse {
  2. private boolean message;
  3. private Integer id;
  4. public boolean getMessage () {
  5. return message;
  6. }
  7. public void setMessage (boolean message) {
  8. this.message = message;
  9. }
  10. public Integer getId () {
  11. return id;
  12. }
  13. public void setId (Integer id) {
  14. this.id = id;
  15. }
  16. }



七  配置文件

application.xml


   
   
    
    
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  5. xmlns:context= "http://www.springframework.org/schema/context"
  6. xmlns:tx= "http://www.springframework.org/schema/tx"
  7. xmlns:dubbo= "http://code.alibabatech.com/schema/dubbo"
  8. xmlns:p= "http://www.springframework.org/schema/p"
  9. xmlns:aop= "http://www.springframework.org/schema/aop"
  10. xmlns:rabbit= "http://www.springframework.org/schema/rabbit"
  11. xsi:schemaLocation= "http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  13. http://www.springframework.org/schema/beans
  14. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  15. http://www.springframework.org/schema/context
  16. http://www.springframework.org/schema/context/spring-context-2.5.xsd
  17. http://www.springframework.org/schema/tx
  18. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  19. http://code.alibabatech.com/schema/dubbo
  20. http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  21. http://www.springframework.org/schema/aop
  22. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  23. http://www.springframework.org/schema/rabbit
  24. http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
  25. <!-- 外部属性文件 -->
  26. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  27. <property name="locations">
  28. <list>
  29. <value>classpath:jdbc.properties </value>
  30. </list>
  31. </property>
  32. </bean>
  33. <!-- 扫描注解组件并且自动的注入 -->
  34. <context:component-scan base-package="com.XXX.demo" />
  35. <mvc:annotation-driven/>
  36. <!-- 配置静态资源访问目录 -->
  37. <mvc:resources mapping="/resources/**" location="/resources/"/>
  38. <!-- JSP视图解析器 -->
  39. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  40. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  41. <property name="prefix" value="/WEB-INF/views/"/>
  42. <property name="suffix" value=".jsp"/>
  43. </bean>
  44. <!-- JSON解析器 -->
  45. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  46. <property name="messageConverters">
  47. <list>
  48. <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
  49. </list>
  50. </property>
  51. </bean>
  52. <!-- 设置数据源 -->
  53. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  54. <property name="driverClass" value="${jdbc.driverClassName}"/>
  55. <!-- 数据库参数配置 -->
  56. <property name="jdbcUrl" value="${jdbc.url}"/>
  57. <property name="user" value="${jdbc.username}"/>
  58. <property name="password" value="${jdbc.password}"/>
  59. <property name="minPoolSize" value="${c3p0.miniPoolSize}"/>
  60. <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
  61. <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
  62. <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
  63. <!-- 超时20秒 -->
  64. <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
  65. </bean>
  66. <!-- 声明事务为注解驱动 -->
  67. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  68. <property name="dataSource" ref="dataSource" />
  69. </bean>
  70. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  71. <tx:attributes>
  72. <tx:method name="*" read-only="false" rollback-for="Exception,RuntimeException" propagation="REQUIRED"/>
  73. </tx:attributes>
  74. </tx:advice>
  75. <aop:config proxy-target-class="true">
  76. <aop:pointcut id="serviceManage" expression="execution(* com.XXX.demo.service..*(..))"/>
  77. <aop:advisor pointcut-ref="serviceManage" advice-ref="txAdvice"/>
  78. </aop:config>
  79. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  80. <property name="dataSource" ref="dataSource" />
  81. <property name="configLocation" value="classpath:config/mybatis-config.xml" />
  82. </bean>
  83. <!-- Dao -->
  84. <bean id="itemDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  85. <property name="mapperInterface" value="com.XXX.demo.dao.ItemDao" />
  86. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  87. </bean>
  88. </beans>


八  页面效果


http://localhost:8080/springJqgrid/main/items


九 总结

由于;

1 缺少值类型校验

2 缺少页面查询条件输入

所以这个例子离实际的应用还有一段距离。


十 鸣谢

http://krams915.blogspot.com/2010/12/jqgrid-and-spring-3-mvc-integration.html
jqGrid and Spring 3 MVC Integration Tutorial

http://blog.csdn.net/kakaxi_77/article/details/46671249
Jqgrid+Struts2实现的增删改查

http://gongm-24.iteye.com/blog/1275430
JqGrid4.2实践-2-集成Spring MVC


---------------------------------------------------------------------------

*备注:

①值类型的校验应该使用custom_func,但我试过了,没起作用。目前原因未明。


--------------------------------------------------------------------------

【补充】

2017-05-18 补充了页面条件输入查询


说明:

①输入条件就是在页面加一个div

②js:


   
   
    
    
  1. function searchReload( ){
  2. var client = $( "#client"). val();
  3. var amount = $( "#amount"). val();
  4. $( "#gridTable"). jqGrid( "setGridParam",
  5. {
  6. url: "${basePath}/itCrud/list",
  7. mtype: 'POST',
  8. postData:{
  9. client:client,
  10. amount:amount
  11. },
  12. datatype: "json"
  13. }). trigger( "reloadGrid");
  14. }

Description:
setGridParam:是jqGrid中的一个方法,表示设置grid的参数
url:这是grid的参数,表示数据的获取路径。grid中的数据就是通过这个url来获取的
postData:表示参数, 请求url时postData中的参数将会被发送到后台。
trigger: 这也是jqGrid的方法,该方法和setGridParam配合使用可以重新加载grid,$("").setGridParam().trigger("reloadGrid");

最近基于之前jqgrid+struts的基础上,做了一个jqgrid+spring的例子,大家请上眼。

零:

工程项目图:


一 View


   
   
  
  
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <%@ include file="/resources/common/include/header.jsp" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  8. <title>jqgrid demo </title>
  9. <!-- JQuery CSS -->
  10. <link rel="stylesheet" href="${basePath}/resources/plugin/jquery-ui-themes-1.8.14/themes/redmond/jquery-ui.css" type="text/css" />
  11. <!-- jqGrid CSS -->
  12. <link rel="stylesheet" href="${basePath}/resources/plugin/jqGrid-4.5.4/css/ui.jqgrid.css" type="text/css" />
  13. <!-- The actual JQuery code -->
  14. <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js" > </script>
  15. <!-- The JQuery UI code -->
  16. <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"> </script>
  17. <!-- The jqGrid language file code-->
  18. <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/i18n/grid.locale-cn.js"> </script>
  19. <!-- The atual jqGrid code -->
  20. <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/jquery.jqGrid.src.js"> </script>
  21. <script type="text/javascript">
  22. $( function( ){
  23. $( "#gridTable"). jqGrid({
  24. url: "${basePath}/itCrud/list",
  25. datatype: "json",
  26. mtype : "post",
  27. height: 250,
  28. colNames:[ 'Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
  29. colModel:[
  30. { name: 'id', index: 'id', width: 55, editable: true, editoptions:{ readonly: true}, sorttype: 'int'},
  31. { name: 'invdate', index: 'invdate', width: 90, editable: true},
  32. { name: 'name', index: 'name asc, invdate', width: 100, editable: true},
  33. { name: 'amount', index: 'amount', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  34. { name: 'tax', index: 'tax', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  35. { name: 'total', index: 'total', width: 80, align: "right", editable: true, editrules:{ number: true}, sorttype: 'number', formatter: 'number'},
  36. { name: 'note', index: 'note', width: 150, sortable: false, editable: true}
  37. ],
  38. sortname: 'id',
  39. sortorder: 'asc',
  40. /*editurl: 'server.php', */
  41. viewrecords: true,
  42. rowNum: 10,
  43. rowList:[ 10, 20, 30],
  44. prmNames : {
  45. search : "search"
  46. },
  47. jsonReader : {
  48. root : "rows",
  49. page: "page",
  50. total: "total",
  51. records : "records",
  52. repeatitems : false
  53. },
  54. pager: "#gridPager",
  55. caption: "jqgrid CRUD demo",
  56. hidegrid : false
  57. });
  58. $( '#gridTable'). jqGrid( 'navGrid', '#gridPager',{
  59. refresh: true,
  60. edit: true,
  61. add: true,
  62. del: true,
  63. search: false,
  64. addfunc:openDialog4Adding,
  65. editfunc:openDialog4Updating,
  66. delfunc:openDialog4Deleting
  67. });
  68. //配置对话框
  69. $( "#consoleDlg"). dialog({
  70. autoOpen: false,
  71. modal: true //设置对话框为模态对话框
  72. });
  73. });
  74. var openDialog4Adding = function( ) {
  75. var consoleDlg = $( "#consoleDlg");
  76. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  77. consoleDlg. find( "input"). removeAttr( "disabled"). val( "");
  78. // dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  79. // dialogButtonPanel.find("button:contains('新增')").show();
  80. consoleDlg. dialog({
  81. title: "新增",
  82. resizable: false,
  83. width: 480,
  84. buttons:{
  85. "取消": function( ){
  86. $( "#consoleDlg"). dialog( "close");
  87. },
  88. "新增":addItem
  89. }
  90. });
  91. consoleDlg. dialog( "open");
  92. };
  93. var openDialog4Updating = function( ) {
  94. var consoleDlg = $( "#consoleDlg");
  95. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  96. consoleDlg. find( "input"). removeAttr( "disabled");
  97. /* dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  98. dialogButtonPanel.find("button:contains('修改')").show(); */
  99. consoleDlg. dialog({
  100. title: "修改",
  101. resizable: false,
  102. width: 480,
  103. buttons:{
  104. "取消": function( ){
  105. $( "#consoleDlg"). dialog( "close");
  106. },
  107. "修改":editItem
  108. }
  109. });
  110. loadSelectedRowData();
  111. consoleDlg. dialog( "open");
  112. };
  113. var openDialog4Deleting = function( ) {
  114. var consoleDlg = $( "#consoleDlg");
  115. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  116. consoleDlg. find( "input"). attr( "disabled", true);
  117. /*
  118. dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  119. dialogButtonPanel.find("button:contains('删除')").show();
  120. consoleDlg.dialog("option", "title", "delete record");
  121. */
  122. consoleDlg. dialog({
  123. title: "删除",
  124. resizable: false,
  125. width: 480,
  126. buttons:{
  127. "取消": function( ){
  128. $( "#consoleDlg"). dialog( "close");
  129. },
  130. "删除":deleteItem
  131. }
  132. });
  133. loadSelectedRowData();
  134. consoleDlg. dialog( "open");
  135. };
  136. var loadSelectedRowData = function( ){
  137. //2016-03-18 当前选中的行
  138. var selectedRowId = $( "#gridTable"). jqGrid( "getGridParam", "selrow");
  139. //获得当前行各项属性
  140. var rowData = $( "#gridTable"). jqGrid( "getRowData",selectedRowId);
  141. if (!selectedRowId) {
  142. alert( "请先选择需要编辑的行!");
  143. return false;
  144. } else {
  145. var consoleDlg = $( "#consoleDlg");
  146. consoleDlg. find( "#selectId"). val(rowData. id);
  147. consoleDlg. find( "#invdate"). val(rowData. invdate);
  148. consoleDlg. find( "#name"). val(rowData. name);
  149. consoleDlg. find( "#amount"). val(rowData. amount);
  150. consoleDlg. find( "#tax"). val(rowData. tax);
  151. consoleDlg. find( "#total"). val(rowData. total);
  152. consoleDlg. find( "#note"). val(rowData. note);
  153. }
  154. };
  155. var openDialog4Deleting = function( ) {
  156. var consoleDlg = $( "#consoleDlg");
  157. // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");
  158. consoleDlg. find( "input"). attr( "disabled", true);
  159. /*
  160. dialogButtonPanel.find("button:not(:contains('取消'))").hide();
  161. dialogButtonPanel.find("button:contains('删除')").show();
  162. consoleDlg.dialog("option", "title", "delete record");
  163. */
  164. consoleDlg. dialog({
  165. title: "删除",
  166. resizable: false,
  167. width: 480,
  168. buttons:{
  169. "取消": function( ){
  170. $( "#consoleDlg"). dialog( "close");
  171. },
  172. "删除":deleteItem
  173. }
  174. });
  175. loadSelectedRowData();
  176. consoleDlg. dialog( "open");
  177. };
  178. var addItem = function( ){
  179. var consoleDlg = $( "#consoleDlg");
  180. var invdate = $. trim(consoleDlg. find( "#invdate"). val());
  181. var name = $. trim(consoleDlg. find( "#name"). val());
  182. var amount = $. trim(consoleDlg. find( "#amount"). val());
  183. var tax = $. trim(consoleDlg. find( "#tax"). val());
  184. var total = $. trim(consoleDlg. find( "#total"). val());
  185. var note = $. trim(consoleDlg. find( "#note"). val());
  186. var params = {
  187. "invdate" : invdate,
  188. "name" : name,
  189. "amount" : amount,
  190. "tax" : tax,
  191. "total" : total,
  192. "note" : note
  193. };
  194. $. ajax({
  195. url: "${basePath}/itCrud/add",
  196. data : params,
  197. dataType : "json",
  198. cache : false,
  199. success : function( response, textStatus) {
  200. /* alert("id123-->" + response.id + "; message-->" + response.message); */
  201. if (response. message == true) {
  202. var dataRow = {
  203. id : response. id, //从server端获得系统分配的id
  204. invdate : invdate,
  205. name : name,
  206. amount : amount,
  207. tax : tax,
  208. total : total,
  209. note : note
  210. };
  211. /*
  212. var srcrowid = $("#gridTable").jqGrid("getGridParam",
  213. "selrow");
  214. */
  215. $( "#gridTable"). jqGrid( "addRowData",
  216. response. id, dataRow, "last"); //将新行插入到末尾
  217. consoleDlg. dialog( "close");
  218. alert( "添加成功!");
  219. } else{
  220. alert( "添加失败!");
  221. }
  222. },
  223. error : function( textStatus, e) {
  224. alert( "系统ajax交互错误: " + textStatus);
  225. }
  226. });
  227. };
  228. var editItem = function( ){
  229. var consoleDlg = $( "#consoleDlg");
  230. var id = $. trim(consoleDlg. find( "#selectId"). val());
  231. var tempInvdate = $. trim(consoleDlg. find( "#invdate"). val());
  232. var invdate = tempInvdate. substring( 0, 10);
  233. var name = $. trim(consoleDlg. find( "#name"). val());
  234. var amount = $. trim(consoleDlg. find( "#amount"). val());
  235. var tax = $. trim(consoleDlg. find( "#tax"). val());
  236. var total = $. trim(consoleDlg. find( "#total"). val());
  237. var note = $. trim(consoleDlg. find( "#note"). val());
  238. var params = {
  239. "id" : id,
  240. "invdate" : invdate,
  241. "name" : name,
  242. "amount" : amount,
  243. "tax" : tax,
  244. "total" : total,
  245. "note" : note
  246. };
  247. $. ajax({
  248. url: "${basePath}/itCrud/edit",
  249. data : params,
  250. dataType : "json",
  251. cache : false,
  252. success : function( response, textStatus) {
  253. // alert("id-->" + response.id + "; message-->" + response.message);
  254. if (response. message == true) {
  255. var dataRow = {
  256. selectId : id,
  257. invdate : invdate,
  258. name : name,
  259. amount : amount,
  260. tax : tax,
  261. total : total,
  262. note : note
  263. };
  264. /*
  265. var srcrowid = $("#gridTable").jqGrid("getGridParam",
  266. "selrow");
  267. */
  268. //将表格中对应记录更新一下
  269. $( "#gridTable"). jqGrid( "setRowData", id, dataRow);
  270. consoleDlg. dialog( "close");
  271. alert( "修改成功!");
  272. } else{
  273. alert( "修改失败!");
  274. }
  275. },
  276. error : function( textStatus, e) {
  277. alert( "系统ajax交互错误: " + textStatus);
  278. }
  279. });
  280. }
  281. var deleteItem = function( ){
  282. var consoleDlg = $( "#consoleDlg");
  283. var id = $. trim(consoleDlg. find( "#selectId"). val());
  284. var tempInvdate = $. trim(consoleDlg. find( "#invdate"). val());
  285. var invdate = tempInvdate. substring( 0, 10);
  286. var name = $. trim(consoleDlg. find( "#name"). val());
  287. var amount = $. trim(consoleDlg. find( "#amount"). val());
  288. var tax = $. trim(consoleDlg. find( "#tax"). val());
  289. var total = $. trim(consoleDlg. find( "#total"). val());
  290. var note = $. trim(consoleDlg. find( "#note"). val());
  291. var params = {
  292. "id" : id,
  293. "invdate" : invdate,
  294. "name" : name,
  295. "amount" : amount,
  296. "tax" : tax,
  297. "total" : total,
  298. "note" : note
  299. };
  300. $. ajax({
  301. url: "${basePath}/itCrud/delete",
  302. data : params,
  303. dataType : "json",
  304. cache : false,
  305. success : function( response, textStatus) {
  306. // alert("id-->" + response.id + "; message-->" + response.message);
  307. if (response. message == true) {
  308. $( "#gridTable"). jqGrid( "delRowData", id);
  309. consoleDlg. dialog( "close");
  310. alert( "删除成功!");
  311. } else{
  312. alert( "删除失败!");
  313. }
  314. },
  315. error : function( textStatus, e) {
  316. alert( "系统ajax交互错误: " + textStatus);
  317. }
  318. });
  319. }
  320. </script>
  321. </head>
  322. <body>
  323. <table id="gridTable"> </table>
  324. <div id="gridPager"> </div>
  325. <div id="consoleDlg" style="display:none">
  326. <form id="consoleForm">
  327. <input type="hidden" id="selectId"/>
  328. <table class="formTable">
  329. <tr>
  330. <th>Date </th>
  331. <td> <input type="text" class="textField" id="invdate" name="invdate" />
  332. </td>
  333. </tr>
  334. <tr>
  335. <th>Client </th>
  336. <td> <input type="text" class="textField" id="name" name="name" />
  337. </td>
  338. </tr>
  339. <tr>
  340. <th>Amount </th>
  341. <td> <input type="text" class="textField" id="amount" name="amount" />
  342. </td>
  343. </tr>
  344. <tr>
  345. <th>Tax </th>
  346. <td> <input type="text" class="textField" id="tax" name="tax" />
  347. </td>
  348. </tr>
  349. <tr>
  350. <th>Total </th>
  351. <td> <input type="text" class="textField" id="total" name="total" />
  352. </td>
  353. </tr>
  354. <tr>
  355. <th>Notes </th>
  356. <td> <input type="text" class="textField" id="note" name="note" />
  357. </td>
  358. </tr>
  359. </table>
  360. </form>
  361. </div>
  362. </body>
  363. </html>


二 Model


   
   
  
  
  1. package com.yangw.demo.pojo;
  2. import com.yangw.demo.base.BasePojo;
  3. public class Item extends BasePojo {
  4. private static final long serialVersionUID = 1L;
  5. private int id;
  6. private String invdate;
  7. private String name;
  8. private double amount;
  9. private double tax;
  10. private double total;
  11. private String note;
  12. public int getId () {
  13. return id;
  14. }
  15. public void setId (int id) {
  16. this.id = id;
  17. }
  18. public String getInvdate () {
  19. return invdate;
  20. }
  21. public void setInvdate (String invdate) {
  22. this.invdate = invdate;
  23. }
  24. public String getName () {
  25. return name;
  26. }
  27. public void setName (String name) {
  28. this.name = name;
  29. }
  30. public double getAmount () {
  31. return amount;
  32. }
  33. public void setAmount (double amount) {
  34. this.amount = amount;
  35. }
  36. public double getTax () {
  37. return tax;
  38. }
  39. public void setTax (double tax) {
  40. this.tax = tax;
  41. }
  42. public double getTotal () {
  43. return total;
  44. }
  45. public void setTotal (double total) {
  46. this.total = total;
  47. }
  48. public String getNote () {
  49. return note;
  50. }
  51. public void setNote (String note) {
  52. this.note = note;
  53. }
  54. }


三 Action

1 MediatorController


   
   
  
  
  1. @Controller
  2. @RequestMapping("/main")
  3. public class MediatorController {
  4. @RequestMapping(value = "/items", method = RequestMethod.GET)
  5. public String getItemPage (){
  6. return "listView";
  7. }
  8. }


2 JqDemoController


   
   
  
  
  1. @Controller
  2. @RequestMapping(value={"/itCrud"})
  3. public class JqDemoController extends BaseController {
  4. @Autowired
  5. private IItemService<Item, Integer> itemService;
  6. private List<Item> dataList;
  7. @RequestMapping(value={"/list"})
  8. public @ResponseBody DataResponse<Item> showList (
  9. Item item,
  10. @RequestParam(defaultValue="1",value="page") String page,
  11. @RequestParam(defaultValue="10",value="rows") String rows
  12. ){
  13. int records; //总记录数
  14. int totalPages; //总页数
  15. int pageSize = StringUtils.isEmpty(rows) ? 10 : Integer.valueOf(rows); //每页显示记录数
  16. int currPage = StringUtils.isEmpty(page) ? 1 : Integer.valueOf(page); //当前页码
  17. DataResponse<Item> response = new DataResponse<Item>();
  18. try {
  19. records = itemService.getEntityCount(item);
  20. totalPages = (records + pageSize - 1) / pageSize;
  21. int start = pageSize * (currPage - 1) + 1;
  22. start = (start < 0) ? 0 : start;
  23. int stop = currPage * pageSize;
  24. item.setStart(start);
  25. item.setStop(stop);
  26. dataList = itemService.searchEntityList(item);
  27. response.setRecords(String.valueOf(records));
  28. response.setTotal(String.valueOf(totalPages));
  29. response.setPage(String.valueOf(currPage));
  30. response.setRows(dataList);
  31. } catch (Exception e) {
  32. // TODO Auto-generated catch block
  33. e.printStackTrace();
  34. }
  35. return response;
  36. }
  37. @RequestMapping(value={"/add"})
  38. public @ResponseBody ResultResponse add (Item item) throws Exception{
  39. ResultResponse response = new ResultResponse();
  40. try {
  41. System.out.println(item);
  42. itemService.insertEntity(item);
  43. response.setId( 100);
  44. response.setMessage( true);
  45. } catch (Exception e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. response.setMessage( false);
  49. throw e;
  50. }
  51. return response;
  52. }
  53. @RequestMapping(value={"/edit"})
  54. public @ResponseBody ResultResponse edit (Item item) throws Exception{
  55. ResultResponse response = new ResultResponse();
  56. try {
  57. System.out.println(item);
  58. itemService.updateEntity(item);
  59. response.setMessage( true);
  60. } catch (Exception e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. response.setMessage( false);
  64. throw e;
  65. }
  66. return response;
  67. }
  68. @RequestMapping(value={"/delete"})
  69. public @ResponseBody ResultResponse delete (Item item) throws Exception{
  70. ResultResponse response = new ResultResponse();
  71. try {
  72. System.out.println(item);
  73. itemService.deleteEntity(item);
  74. response.setMessage( true);
  75. } catch (Exception e) {
  76. // TODO Auto-generated catch block
  77. e.printStackTrace();
  78. response.setMessage( false);
  79. throw e;
  80. }
  81. return response;
  82. }
  83. public List<Item> getDataList () {
  84. return dataList;
  85. }
  86. public void setDataList (List<Item> dataList) {
  87. this.dataList = dataList;
  88. }
  89. }



四 Service

1 BaseService


   
   
  
  
  1. public interface BaseService<Entity extends Serializable,Query extends Object> {
  2. /**
  3. * 添加 实体
  4. * sqlKey insertEntity
  5. * @param entity
  6. * @return
  7. * @throws Exception
  8. */
  9. public Query insertEntity (Entity entity) throws Exception;
  10. /**
  11. * 修改 实体
  12. * sqlKey updateEntity
  13. * @param entity
  14. * @return
  15. * @throws Exception
  16. */
  17. public int updateEntity (Entity entity) throws Exception;
  18. /**
  19. * 删除 实体
  20. * sqlKey deleteEntityById
  21. * @param entity
  22. * @return
  23. * @throws Exception
  24. */
  25. public int deleteEntity (Entity entity) throws Exception;
  26. /**
  27. * 根据实体参数查找单个数据
  28. * sqlKey searchEntity
  29. * @param sqlMap
  30. * @param query
  31. * @return
  32. * @throws Exception
  33. */
  34. public Entity searchEntity (Entity entity) throws Exception;
  35. /**
  36. * 查询 实体列表
  37. * sqlKey searchEntityList
  38. * @param query
  39. * @return
  40. * @throws Exception
  41. */
  42. public List<Entity> searchEntityList (Entity entity) throws Exception;
  43. /**
  44. * 查询总数
  45. * @param sqlMap
  46. * @param query
  47. * @throws Exception
  48. */
  49. public int getEntityCount (Entity entity) throws Exception;
  50. }

2 ItemServiceImpl


   
   
  
  
  1. @Service
  2. public class ItemServiceImpl extends BaseServiceSupport<Item, Integer> implements IItemService<Item, Integer> {
  3. @Resource(name="itemDao")
  4. private ItemDao itemDao;
  5. }

五 Dao层

1 BaseDao


   
   
  
  
  1. public interface BaseDao<Entity extends Serializable, Query extends Object> {
  2. /**
  3. * 添加 实体
  4. * @param entity
  5. * @return
  6. * @throws SQLException
  7. */
  8. public Query insertEntity (Entity entity) throws SQLException;
  9. /**
  10. * 修改 实体
  11. * @param entity
  12. * @return
  13. * @throws SQLException
  14. */
  15. public int updateEntity (Entity entity) throws SQLException;
  16. /**
  17. * 删除 实体
  18. * @param entity
  19. * @return
  20. * @throws SQLException
  21. */
  22. public int deleteEntity (Entity entity) throws SQLException;
  23. /**
  24. * 根据实体参数查找单个数据
  25. * @param sqlMap
  26. * @param query
  27. * @return
  28. * @throws SQLException
  29. */
  30. public Entity searchEntity (Entity entity) throws SQLException;
  31. /**
  32. * 查询 实体列表
  33. * @param query
  34. * @return
  35. * @throws SQLException
  36. */
  37. public List<Entity> searchEntityList (Entity entity) throws SQLException;
  38. /**
  39. * 查询总数
  40. * @param sqlMap
  41. * @param query
  42. * @throws SQLException
  43. */
  44. public int getEntityCount (Entity entity) throws SQLException;
  45. }


六 json

1 DataResponse


   
   
  
  
  1. public class DataResponse<T> {
  2. private String page;
  3. private String total;
  4. private String records;
  5. private List<T> rows;
  6. private Map<String, Object> userdata;
  7. public String getPage () {
  8. return page;
  9. }
  10. public void setPage (String page) {
  11. this.page = page;
  12. }
  13. public String getTotal () {
  14. return total;
  15. }
  16. public void setTotal (String total) {
  17. this.total = total;
  18. }
  19. public String getRecords () {
  20. return records;
  21. }
  22. public void setRecords (String records) {
  23. this.records = records;
  24. }
  25. public List<T> getRows () {
  26. return rows;
  27. }
  28. public void setRows (List<T> rows) {
  29. this.rows = rows;
  30. }
  31. public Map<String, Object> getUserdata () {
  32. return userdata;
  33. }
  34. public void setUserdata (Map<String, Object> userdata) {
  35. this.userdata = userdata;
  36. }
  37. }


2 ResultResponse


   
   
  
  
  1. public class ResultResponse {
  2. private boolean message;
  3. private Integer id;
  4. public boolean getMessage () {
  5. return message;
  6. }
  7. public void setMessage (boolean message) {
  8. this.message = message;
  9. }
  10. public Integer getId () {
  11. return id;
  12. }
  13. public void setId (Integer id) {
  14. this.id = id;
  15. }
  16. }



七  配置文件

application.xml


   
   
  
  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  5. xmlns:context= "http://www.springframework.org/schema/context"
  6. xmlns:tx= "http://www.springframework.org/schema/tx"
  7. xmlns:dubbo= "http://code.alibabatech.com/schema/dubbo"
  8. xmlns:p= "http://www.springframework.org/schema/p"
  9. xmlns:aop= "http://www.springframework.org/schema/aop"
  10. xmlns:rabbit= "http://www.springframework.org/schema/rabbit"
  11. xsi:schemaLocation= "http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  13. http://www.springframework.org/schema/beans
  14. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  15. http://www.springframework.org/schema/context
  16. http://www.springframework.org/schema/context/spring-context-2.5.xsd
  17. http://www.springframework.org/schema/tx
  18. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  19. http://code.alibabatech.com/schema/dubbo
  20. http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  21. http://www.springframework.org/schema/aop
  22. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  23. http://www.springframework.org/schema/rabbit
  24. http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
  25. <!-- 外部属性文件 -->
  26. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  27. <property name="locations">
  28. <list>
  29. <value>classpath:jdbc.properties </value>
  30. </list>
  31. </property>
  32. </bean>
  33. <!-- 扫描注解组件并且自动的注入 -->
  34. <context:component-scan base-package="com.XXX.demo" />
  35. <mvc:annotation-driven/>
  36. <!-- 配置静态资源访问目录 -->
  37. <mvc:resources mapping="/resources/**" location="/resources/"/>
  38. <!-- JSP视图解析器 -->
  39. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  40. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  41. <property name="prefix" value="/WEB-INF/views/"/>
  42. <property name="suffix" value=".jsp"/>
  43. </bean>
  44. <!-- JSON解析器 -->
  45. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  46. <property name="messageConverters">
  47. <list>
  48. <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
  49. </list>
  50. </property>
  51. </bean>
  52. <!-- 设置数据源 -->
  53. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  54. <property name="driverClass" value="${jdbc.driverClassName}"/>
  55. <!-- 数据库参数配置 -->
  56. <property name="jdbcUrl" value="${jdbc.url}"/>
  57. <property name="user" value="${jdbc.username}"/>
  58. <property name="password" value="${jdbc.password}"/>
  59. <property name="minPoolSize" value="${c3p0.miniPoolSize}"/>
  60. <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
  61. <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
  62. <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
  63. <!-- 超时20秒 -->
  64. <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
  65. </bean>
  66. <!-- 声明事务为注解驱动 -->
  67. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  68. <property name="dataSource" ref="dataSource" />
  69. </bean>
  70. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  71. <tx:attributes>
  72. <tx:method name="*" read-only="false" rollback-for="Exception,RuntimeException" propagation="REQUIRED"/>
  73. </tx:attributes>
  74. </tx:advice>
  75. <aop:config proxy-target-class="true">
  76. <aop:pointcut id="serviceManage" expression="execution(* com.XXX.demo.service..*(..))"/>
  77. <aop:advisor pointcut-ref="serviceManage" advice-ref="txAdvice"/>
  78. </aop:config>
  79. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  80. <property name="dataSource" ref="dataSource" />
  81. <property name="configLocation" value="classpath:config/mybatis-config.xml" />
  82. </bean>
  83. <!-- Dao -->
  84. <bean id="itemDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
  85. <property name="mapperInterface" value="com.XXX.demo.dao.ItemDao" />
  86. <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  87. </bean>
  88. </beans>


八  页面效果


http://localhost:8080/springJqgrid/main/items


九 总结

由于;

1 缺少值类型校验

2 缺少页面查询条件输入

所以这个例子离实际的应用还有一段距离。


十 鸣谢

http://krams915.blogspot.com/2010/12/jqgrid-and-spring-3-mvc-integration.html
jqGrid and Spring 3 MVC Integration Tutorial

http://blog.csdn.net/kakaxi_77/article/details/46671249
Jqgrid+Struts2实现的增删改查

http://gongm-24.iteye.com/blog/1275430
JqGrid4.2实践-2-集成Spring MVC


---------------------------------------------------------------------------

*备注:

①值类型的校验应该使用custom_func,但我试过了,没起作用。目前原因未明。


--------------------------------------------------------------------------

【补充】

2017-05-18 补充了页面条件输入查询


说明:

①输入条件就是在页面加一个div

②js:


   
   
  
  
  1. function searchReload( ){
  2. var client = $( "#client"). val();
  3. var amount = $( "#amount"). val();
  4. $( "#gridTable"). jqGrid( "setGridParam",
  5. {
  6. url: "${basePath}/itCrud/list",
  7. mtype: 'POST',
  8. postData:{
  9. client:client,
  10. amount:amount
  11. },
  12. datatype: "json"
  13. }). trigger( "reloadGrid");
  14. }

Description:
setGridParam:是jqGrid中的一个方法,表示设置grid的参数
url:这是grid的参数,表示数据的获取路径。grid中的数据就是通过这个url来获取的
postData:表示参数, 请求url时postData中的参数将会被发送到后台。
trigger: 这也是jqGrid的方法,该方法和setGridParam配合使用可以重新加载grid,$("").setGridParam().trigger("reloadGrid");

猜你喜欢

转载自blog.csdn.net/yangyang_VV/article/details/132596951