Jqgrid+Spring实现的增删改查(1)
Jqgrid+Spring实现的增删改查(一)
2 ItemServiceImpl
五 Dao层
最近基于之前jqgrid+struts的基础上,做了一个jqgrid+spring的例子,大家请上眼。
零:
工程项目图:
一 View
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ include file="/resources/common/include/header.jsp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jqgrid demo</title> <!-- JQuery CSS --> <link rel="stylesheet" href="${basePath}/resources/plugin/jquery-ui-themes-1.8.14/themes/redmond/jquery-ui.css" type="text/css" /> <!-- jqGrid CSS --> <link rel="stylesheet" href="${basePath}/resources/plugin/jqGrid-4.5.4/css/ui.jqgrid.css" type="text/css" /> <!-- The actual JQuery code --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js" ></script> <!-- The JQuery UI code --> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script> <!-- The jqGrid language file code--> <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/i18n/grid.locale-cn.js"></script> <!-- The atual jqGrid code --> <script type="text/javascript" src="${basePath}/resources/plugin/jqGrid-4.5.4/js/jquery.jqGrid.src.js"></script> <script type="text/javascript"> $(function(){ $("#gridTable").jqGrid({ url: "${basePath}/itCrud/list", datatype: "json", mtype : "post", height: 250, colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:55, editable:true, editoptions:{readonly:true}, sorttype:'int'}, {name:'invdate',index:'invdate', width:90, editable:true}, {name:'name',index:'name asc, invdate', width:100,editable:true}, {name:'amount',index:'amount', width:80, align:"right",editable:true,editrules:{number:true},sorttype:'number',formatter:'number'}, {name:'tax',index:'tax', width:80, align:"right",editable:true,editrules:{number:true},sorttype:'number',formatter:'number'}, {name:'total',index:'total', width:80,align:"right",editable:true,editrules:{number:true},sorttype:'number',formatter:'number'}, {name:'note',index:'note', width:150, sortable:false,editable:true} ], sortname:'id', sortorder:'asc', /*editurl: 'server.php', */ viewrecords:true, rowNum:10, rowList:[10,20,30], prmNames : { search : "search" }, jsonReader : { root : "rows", page: "page", total: "total", records : "records", repeatitems : false }, pager:"#gridPager", caption: "jqgrid CRUD demo", hidegrid : false }); $('#gridTable').jqGrid('navGrid','#gridPager',{ refresh:true, edit:true, add:true, del:true, search:false, addfunc:openDialog4Adding, editfunc:openDialog4Updating, delfunc:openDialog4Deleting }); //配置对话框 $("#consoleDlg").dialog({ autoOpen:false, modal:true //设置对话框为模态对话框 }); }); var openDialog4Adding = function() { var consoleDlg = $("#consoleDlg"); // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane"); consoleDlg.find("input").removeAttr("disabled").val(""); // dialogButtonPanel.find("button:not(:contains('取消'))").hide(); // dialogButtonPanel.find("button:contains('新增')").show(); consoleDlg.dialog({ title:"新增", resizable:false, width:480, buttons:{ "取消":function(){ $("#consoleDlg").dialog("close"); }, "新增":addItem } }); consoleDlg.dialog("open"); }; var openDialog4Updating = function() { var consoleDlg = $("#consoleDlg"); // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane"); consoleDlg.find("input").removeAttr("disabled"); /* dialogButtonPanel.find("button:not(:contains('取消'))").hide(); dialogButtonPanel.find("button:contains('修改')").show(); */ consoleDlg.dialog({ title:"修改", resizable:false, width:480, buttons:{ "取消":function(){ $("#consoleDlg").dialog("close"); }, "修改":editItem } }); loadSelectedRowData(); consoleDlg.dialog("open"); }; var openDialog4Deleting = function() { var consoleDlg = $("#consoleDlg"); // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane"); consoleDlg.find("input").attr("disabled", true); /* dialogButtonPanel.find("button:not(:contains('取消'))").hide(); dialogButtonPanel.find("button:contains('删除')").show(); consoleDlg.dialog("option", "title", "delete record"); */ consoleDlg.dialog({ title:"删除", resizable:false, width:480, buttons:{ "取消":function(){ $("#consoleDlg").dialog("close"); }, "删除":deleteItem } }); loadSelectedRowData(); consoleDlg.dialog("open"); }; var loadSelectedRowData = function(){ //2016-03-18 当前选中的行 var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow"); //获得当前行各项属性 var rowData = $("#gridTable").jqGrid("getRowData",selectedRowId); if (!selectedRowId) { alert("请先选择需要编辑的行!"); return false; } else { var consoleDlg = $("#consoleDlg"); consoleDlg.find("#selectId").val(rowData.id); consoleDlg.find("#invdate").val(rowData.invdate); consoleDlg.find("#name").val(rowData.name); consoleDlg.find("#amount").val(rowData.amount); consoleDlg.find("#tax").val(rowData.tax); consoleDlg.find("#total").val(rowData.total); consoleDlg.find("#note").val(rowData.note); } }; var openDialog4Deleting = function() { var consoleDlg = $("#consoleDlg"); // var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane"); consoleDlg.find("input").attr("disabled", true); /* dialogButtonPanel.find("button:not(:contains('取消'))").hide(); dialogButtonPanel.find("button:contains('删除')").show(); consoleDlg.dialog("option", "title", "delete record"); */ consoleDlg.dialog({ title:"删除", resizable:false, width:480, buttons:{ "取消":function(){ $("#consoleDlg").dialog("close"); }, "删除":deleteItem } }); loadSelectedRowData(); consoleDlg.dialog("open"); }; var addItem = function(){ var consoleDlg = $("#consoleDlg"); var invdate = $.trim(consoleDlg.find("#invdate").val()); var name = $.trim(consoleDlg.find("#name").val()); var amount = $.trim(consoleDlg.find("#amount").val()); var tax = $.trim(consoleDlg.find("#tax").val()); var total = $.trim(consoleDlg.find("#total").val()); var note = $.trim(consoleDlg.find("#note").val()); var params = { "invdate" : invdate, "name" : name, "amount" : amount, "tax" : tax, "total" : total, "note" : note }; $.ajax({ url:"${basePath}/itCrud/add", data : params, dataType : "json", cache : false, success : function(response, textStatus) { /* alert("id123-->" + response.id + "; message-->" + response.message); */ if (response.message == true) { var dataRow = { id : response.id, //从server端获得系统分配的id invdate : invdate, name : name, amount : amount, tax : tax, total : total, note : note }; /* var srcrowid = $("#gridTable").jqGrid("getGridParam", "selrow"); */ $("#gridTable").jqGrid("addRowData", response.id, dataRow, "last"); //将新行插入到末尾 consoleDlg.dialog("close"); alert("添加成功!"); }else{ alert("添加失败!"); } }, error : function(textStatus, e) { alert("系统ajax交互错误: " + textStatus); } }); }; var editItem = function(){ var consoleDlg = $("#consoleDlg"); var id = $.trim(consoleDlg.find("#selectId").val()); var tempInvdate = $.trim(consoleDlg.find("#invdate").val()); var invdate = tempInvdate.substring(0,10); var name = $.trim(consoleDlg.find("#name").val()); var amount = $.trim(consoleDlg.find("#amount").val()); var tax = $.trim(consoleDlg.find("#tax").val()); var total = $.trim(consoleDlg.find("#total").val()); var note = $.trim(consoleDlg.find("#note").val()); var params = { "id" : id, "invdate" : invdate, "name" : name, "amount" : amount, "tax" : tax, "total" : total, "note" : note }; $.ajax({ url:"${basePath}/itCrud/edit", data : params, dataType : "json", cache : false, success : function(response, textStatus) { // alert("id-->" + response.id + "; message-->" + response.message); if (response.message == true) { var dataRow = { selectId : id, invdate : invdate, name : name, amount : amount, tax : tax, total : total, note : note }; /* var srcrowid = $("#gridTable").jqGrid("getGridParam", "selrow"); */ //将表格中对应记录更新一下 $("#gridTable").jqGrid("setRowData", id, dataRow); consoleDlg.dialog("close"); alert("修改成功!"); }else{ alert("修改失败!"); } }, error : function(textStatus, e) { alert("系统ajax交互错误: " + textStatus); } }); } var deleteItem = function(){ var consoleDlg = $("#consoleDlg"); var id = $.trim(consoleDlg.find("#selectId").val()); var tempInvdate = $.trim(consoleDlg.find("#invdate").val()); var invdate = tempInvdate.substring(0,10); var name = $.trim(consoleDlg.find("#name").val()); var amount = $.trim(consoleDlg.find("#amount").val()); var tax = $.trim(consoleDlg.find("#tax").val()); var total = $.trim(consoleDlg.find("#total").val()); var note = $.trim(consoleDlg.find("#note").val()); var params = { "id" : id, "invdate" : invdate, "name" : name, "amount" : amount, "tax" : tax, "total" : total, "note" : note }; $.ajax({ url:"${basePath}/itCrud/delete", data : params, dataType : "json", cache : false, success : function(response, textStatus) { // alert("id-->" + response.id + "; message-->" + response.message); if (response.message == true) { $("#gridTable").jqGrid("delRowData", id); consoleDlg.dialog("close"); alert("删除成功!"); }else{ alert("删除失败!"); } }, error : function(textStatus, e) { alert("系统ajax交互错误: " + textStatus); } }); } </script> </head> <body> <table id="gridTable"></table> <div id="gridPager"></div> <div id="consoleDlg" style="display:none"> <form id="consoleForm"> <input type="hidden" id="selectId"/> <table class="formTable"> <tr> <th>Date</th> <td><input type="text" class="textField" id="invdate" name="invdate" /> </td> </tr> <tr> <th>Client</th> <td><input type="text" class="textField" id="name" name="name" /> </td> </tr> <tr> <th>Amount</th> <td><input type="text" class="textField" id="amount" name="amount" /> </td> </tr> <tr> <th>Tax</th> <td><input type="text" class="textField" id="tax" name="tax" /> </td> </tr> <tr> <th>Total</th> <td><input type="text" class="textField" id="total" name="total" /> </td> </tr> <tr> <th>Notes</th> <td><input type="text" class="textField" id="note" name="note" /> </td> </tr> </table> </form> </div> </body> </html>
二 Model
package com.yangw.demo.pojo; import com.yangw.demo.base.BasePojo; public class Item extends BasePojo { private static final long serialVersionUID = 1L; private int id; private String invdate; private String name; private double amount; private double tax; private double total; private String note; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInvdate() { return invdate; } public void setInvdate(String invdate) { this.invdate = invdate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public double getTax() { return tax; } public void setTax(double tax) { this.tax = tax; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
三 Action
1 MediatorController
@Controller @RequestMapping("/main") public class MediatorController { @RequestMapping(value = "/items", method = RequestMethod.GET) public String getItemPage(){ return "listView"; } }
@Controller @RequestMapping(value={"/itCrud"}) public class JqDemoController extends BaseController { @Autowired private IItemService<Item, Integer> itemService; private List<Item> dataList; @RequestMapping(value={"/list"}) public @ResponseBody DataResponse<Item> showList( Item item, @RequestParam(defaultValue="1",value="page") String page, @RequestParam(defaultValue="10",value="rows") String rows ){ int records; //总记录数 int totalPages; //总页数 int pageSize = StringUtils.isEmpty(rows) ? 10 : Integer.valueOf(rows); //每页显示记录数 int currPage = StringUtils.isEmpty(page) ? 1 : Integer.valueOf(page); //当前页码 DataResponse<Item> response = new DataResponse<Item>(); try { records = itemService.getEntityCount(item); totalPages = (records + pageSize -1) / pageSize; int start = pageSize * (currPage - 1) + 1; start = (start < 0) ? 0 : start; int stop = currPage * pageSize; item.setStart(start); item.setStop(stop); dataList = itemService.searchEntityList(item); response.setRecords(String.valueOf(records)); response.setTotal(String.valueOf(totalPages)); response.setPage(String.valueOf(currPage)); response.setRows(dataList); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return response; } @RequestMapping(value={"/add"}) public @ResponseBody ResultResponse add(Item item) throws Exception{ ResultResponse response = new ResultResponse(); try { System.out.println(item); itemService.insertEntity(item); response.setId(100); response.setMessage(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); response.setMessage(false); throw e; } return response; } @RequestMapping(value={"/edit"}) public @ResponseBody ResultResponse edit(Item item) throws Exception{ ResultResponse response = new ResultResponse(); try { System.out.println(item); itemService.updateEntity(item); response.setMessage(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); response.setMessage(false); throw e; } return response; } @RequestMapping(value={"/delete"}) public @ResponseBody ResultResponse delete(Item item) throws Exception{ ResultResponse response = new ResultResponse(); try { System.out.println(item); itemService.deleteEntity(item); response.setMessage(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); response.setMessage(false); throw e; } return response; } public List<Item> getDataList() { return dataList; } public void setDataList(List<Item> dataList) { this.dataList = dataList; } }
四 Service
1 BaseService
public interface BaseService<Entity extends Serializable,Query extends Object> { /** * 添加 实体 * sqlKey insertEntity * @param entity * @return * @throws Exception */ public Query insertEntity(Entity entity) throws Exception; /** * 修改 实体 * sqlKey updateEntity * @param entity * @return * @throws Exception */ public int updateEntity(Entity entity) throws Exception; /** * 删除 实体 * sqlKey deleteEntityById * @param entity * @return * @throws Exception */ public int deleteEntity(Entity entity) throws Exception; /** * 根据实体参数查找单个数据 * sqlKey searchEntity * @param sqlMap * @param query * @return * @throws Exception */ public Entity searchEntity(Entity entity)throws Exception; /** * 查询 实体列表 * sqlKey searchEntityList * @param query * @return * @throws Exception */ public List<Entity> searchEntityList(Entity entity) throws Exception; /** * 查询总数 * @param sqlMap * @param query * @throws Exception */ public int getEntityCount(Entity entity) throws Exception; }
2 ItemServiceImpl
@Service public class ItemServiceImpl extends BaseServiceSupport<Item, Integer> implements IItemService<Item, Integer> { @Resource(name="itemDao") private ItemDao itemDao; }
五 Dao层
1 BaseDao
public interface BaseDao<Entity extends Serializable, Query extends Object> { /** * 添加 实体 * @param entity * @return * @throws SQLException */ public Query insertEntity(Entity entity) throws SQLException; /** * 修改 实体 * @param entity * @return * @throws SQLException */ public int updateEntity(Entity entity) throws SQLException; /** * 删除 实体 * @param entity * @return * @throws SQLException */ public int deleteEntity(Entity entity) throws SQLException; /** * 根据实体参数查找单个数据 * @param sqlMap * @param query * @return * @throws SQLException */ public Entity searchEntity(Entity entity)throws SQLException; /** * 查询 实体列表 * @param query * @return * @throws SQLException */ public List<Entity> searchEntityList(Entity entity) throws SQLException; /** * 查询总数 * @param sqlMap * @param query * @throws SQLException */ public int getEntityCount(Entity entity) throws SQLException; }
1 DataResponse
public class DataResponse<T> { private String page; private String total; private String records; private List<T> rows; private Map<String, Object> userdata; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getRecords() { return records; } public void setRecords(String records) { this.records = records; } public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } public Map<String, Object> getUserdata() { return userdata; } public void setUserdata(Map<String, Object> userdata) { this.userdata = userdata; } }
2 ResultResponse
public class ResultResponse { private boolean message; private Integer id; public boolean getMessage() { return message; } public void setMessage(boolean message) { this.message = message; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
七 配置文件
application.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:rabbit="http://www.springframework.org/schema/rabbit" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd"> <!-- 外部属性文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 扫描注解组件并且自动的注入 --> <context:component-scan base-package="com.XXX.demo" /> <mvc:annotation-driven/> <!-- 配置静态资源访问目录 --> <mvc:resources mapping="/resources/**" location="/resources/"/> <!-- JSP视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- JSON解析器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> </list> </property> </bean> <!-- 设置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}"/> <!-- 数据库参数配置 --> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="minPoolSize" value="${c3p0.miniPoolSize}"/> <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/> <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/> <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/> <!-- 超时20秒 --> <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/> </bean> <!-- 声明事务为注解驱动 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" read-only="false" rollback-for="Exception,RuntimeException" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:pointcut id="serviceManage" expression="execution(* com.XXX.demo.service..*(..))"/> <aop:advisor pointcut-ref="serviceManage" advice-ref="txAdvice"/> </aop:config> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> </bean> <!-- Dao --> <bean id="itemDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.XXX.demo.dao.ItemDao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> </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.****.net/kakaxi_77/article/details/46671249
Jqgrid+Struts2实现的增删改查
http://gongm-24.iteye.com/blog/1275430
JqGrid4.2实践-2-集成Spring MVC