SpringMVC+Bootstrap项目
SpringMVC+Bootstrap项目,应用细节记录
一、效果图
二、实现(知识点)
1、前端(html+CSS+js(jQuery)+bootstrap)
a、浏览器标签页显示标题:
<head> <title>资方信息配置</title></head>
b、form表单提交
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <form action="../../gateway/FundInfo/save.cdo" method="post" id="addFundForm" style="float:right" target="frame1" onsubmit="return addFundForm();"> 2 <span style="margin-left: 15px;">资金方名称: <input type="text" id="strFundName" name="strFundName" style="margin-left: 5px;"/></span> 3 <span style="margin-left: 15px;">FundCode【nBorrowMode】: <input id="nFundId" type="number" name="nFundId" style="margin-left: 5px;"/></span> 4 <input id="addFund_btn" class="fundSubmit_btn" type="submit" value="添加" style="margin-left: 5px;" /> 5 </form>
调用js中的 addFundForm() 方法,将数据提交给后台:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 添加资金方 */ 2 function addFundForm() { 3 var strFundName = decodeURIComponent($("#strFundName").val()); 4 var fundId = $("#nFundId").val(); 5 $.ajax({ 6 type: "get", 7 url: "../../gateway/FundInfo/save.cdo?strFundName="+strFundName + "&nFundId="+fundId, 8 success: function (data) { 9 if (data == "success") { 10 alert("添加 ["+strFundName+" 资金方] 成功!"); 11 // 再次加载 资金方下拉列表 12 initFund(); 13 } 14 }, 15 error: function () { 16 alert("添加失败"); 17 return false; 18 }, 19 complete: function () { 20 } 21 }); 22 23 return false; 24 }
c、select下拉列表(主要,从【默认赋值】、【选项变动,传值】两个点介绍)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<select id="fundSelect" class="baffleParamTypeType" name="baffleParamTypeType"> <option value="number">***</option> </select>
js部分
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 (function () { 2 $(document).ready(function () { 3 // 读取网页地址 4 var thisURL = document.URL; 5 nFundId = GetArgsFromHref(thisURL,"nFundId"); 6 if(nFundId == null || nFundId == "") 7 { 8 nFundId = 0; 9 } 10 11 // 页面初始化 12 initFund(nFundId); 13 14 /** 加载 loadFund 表格数据 **/ 15 // loadFund(nFundId); // 后面再详细介绍 16 17 // 下拉列表选项变动 18 $('#fundSelect').change(function () 19 { 20 var fundEle = $(this).children('option:selected'); 21 nFundId = fundEle.val();//这就是selected的值 22 strFundName = fundEle.text(); 23 /** 加载 loadFund 表格数据**/ 24 // loadFund(nFundId); // 后面再详细介绍 25 }); 26 }); 27 28 })(); 29 30 var nFundId = 0; 31 var strFundName = ""; 32 33 /** 页面初始化 **/ 34 function initFund(nFundId) 35 { 36 var fundSelect = $("#fundSelect"); 37 fundSelect.empty(); 38 39 // 获取资金方 40 $.ajax({ 41 type: "get", 42 url: "../../gateway/FundInfo/getFundAll.cdo", 43 // data: {strJson: JSON.stringify("")}, 44 success: function (data, status) { 45 var jsonObj = JSON.parse(data) 46 var fundLength = jsonObj.length; 47 var flag = false; 48 for (var i = 0; i < fundLength; i++) { 49 var fund = jsonObj[i]; 50 var selEle = fund.nFundId; 51 var option = ""; 52 if(nFundId == selEle) 53 { 54 option = $("<option selected = \"selected\">").text(fund.strFundName).val(fund.nFundId); 55 nFundId = selEle; 56 strFundName = fund.strFundName; 57 flag = true; 58 }else{ 59 option = $("<option>").text(fund.strFundName).val(fund.nFundId); 60 } 61 62 fundSelect.append(option); 63 } 64 if(!flag) 65 { 66 nFundId = jsonObj[0].nFundId; 67 strFundName = jsonObj[0].strFundName; 68 } 69 70 }, 71 error: function () { 72 alert("查询失败"); 73 return; 74 }, 75 complete: function () { 76 return; 77 } 78 }); 79 }
d、面板组: panel-group
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <div class="panel-group" id="accordion"> 2 <div class="panel panel-default"> 3 <div class="panel-heading"> 4 <h4 class="panel-title"> 5 <a data-toggle="collapse" data-parent="#accordion" 6 href="#collapseOne"> 7 资方信息FundInfo配置 8 </a> 9 </h4> 10 </div> 11 <div id="collapseOne" class="panel-collapse collapse in"> 12 13 <div class="panel-body"> 14 <div class="mid"> 15 <div> 16 <table class="table table-striped table-hover" id="mainFundInfoTable" 17 data-show-export="true" > 18 </table> 19 </div> 20 21 </div> 22 </div> 23 24 </div> 25 </div> 26 <div class="panel panel-default"> 27 <div class="panel-heading"> 28 <h4 class="panel-title"> 29 <a data-toggle="collapse" data-parent="#accordion" 30 href="#collapseTwo"> 31 资方账户信息 FundAccountInfo 配置 32 </a> 33 </h4> 34 </div> 35 <div id="collapseTwo" class="panel-collapse collapse"> 36 <div class="panel-body"> 37 <div class="mid"> 38 <div> 39 <table class="table table-striped table-hover" id="mainFundAccountInfoTable" 40 data-show-export="true"> 41 42 </table> 43 </div> 44 </div> 45 </div> 46 </div> 47 </div> 48 <div class="panel panel-default"> 49 <div class="panel-heading"> 50 <h4 class="panel-title"> 51 <a data-toggle="collapse" data-parent="#accordion" 52 href="#collapseThree"> 53 资方参数信息 FundParam 配置 54 </a> 55 </h4> 56 </div> 57 <div id="collapseThree" class="panel-collapse collapse"> 58 <div class="panel-body"> 59 <div class="bottom"> 60 <div> 61 <table class="table table-striped table-hover" id="mainFundParamTable" 62 data-show-export="true"> 63 </table> 64 </div> 65 </div> 66 67 </div> 68 69 </div> 70 </div> 71 <div class="panel panel-default"> 72 <div class="panel-heading"> 73 <h4 class="panel-title"> 74 <a data-toggle="collapse" data-parent="#accordion" 75 href="#collapseFourth"> 76 资方参数信息 FundRelation 配置 77 </a> 78 </h4> 79 </div> 80 <div id="collapseFourth" class="panel-collapse collapse"> 81 <div class="panel-body"> 82 <div class="bottom"> 83 <span class="param_wrap"> 84 <div> 85 <table class="table table-striped table-hover" id="mainFundRelationTable" 86 data-show-export="true"> 87 </table> 88 </div> 89 </span> 90 </div> 91 92 </div> 93 94 </div> 95 </div> 96 </div>
e、带回调方法的全局方法调用
i、全局方法声明(带回调方法)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * 公共删除 3 * 带回调方法的全局方法调用 4 * freshHandler 回调方法 5 * **/ 6 var publicDelRow; 7 (function () { 8 publicDelRow = { 9 delRow:function(rows,optFund,freshHandler){ 10 if(rows.length<=0){ 11 console.log(rows.name); 12 alert("请至少选中一行") 13 return; 14 } 15 16 var lIds = new Array(rows.length); 17 for (var i=0; i < rows.length; i++) 18 { 19 var lId = rows[i].lId; 20 lIds[i] = lId; 21 } 22 23 // 调用js 批量删除配置记录 24 $.MsgBox.Confirm("温馨提示", "确定要删除么?", function () { delRows(optFund, lIds, freshHandler); }); 25 26 } 27 } 28 })(); 29 30 31 /** 删除 **/ 32 function delRows(optFund, lIds, freshHandler){ 33 var url = "../../gateway/"+optFund+"/del.cdo?lIds="+lIds; 34 $.ajax({ 35 type: "get", 36 url: url, 37 success: function (data, status) { 38 if (data == "success") { 39 if (typeof(freshHandler) == 'function') { 40 freshHandler(); 41 } 42 } 43 }, 44 error: function () { 45 alert("删除失败"); 46 }, 47 complete: function () { 48 49 } 50 51 }); 52 }
ii、调用全局方法(带回调方法)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $('#delFundAccountInfoRowbtn').unbind('click').click(function () { 2 var rows = $('#fundAccountInfoTable').bootstrapTable('getSelections'); 3 var optFund = "FundAccountInfo"; 4 /** 5 * 带回调方法的全局方法调用 6 * freshHandler 回调方法 7 */ 8 publicDelRow.delRow(rows,optFund,freshHandler); 9 }); 10 11 /** 12 * 刷新(提供回调) 13 */ 14 function freshHandler() { 15 var opt = { 16 url: url, 17 silent: true, 18 query:{ 19 type:1, 20 level:2 21 } 22 }; 23 24 $("#fundAccountInfoTable").bootstrapTable('refresh', opt); 25 }
f、js获取网页地址,并从地址中读取参数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 读取网页链接地址 2 var thisURL = document.URL; 3 // 从地址中取出,指定参数 4 nFundId = GetArgsFromHref(thisURL,"nFundId"); 5 6 /** 7 * 从 Href 中获取参数 8 * @param sHref 9 * @param sArgName 10 * @returns {string} 11 * @constructor 12 */ 13 function GetArgsFromHref(sHref, sArgName) 14 { 15 var args = sHref.split("?"); 16 var retval = ""; 17 if(args[0] == sHref) /*参数为空*/ 18 { 19 return retval; /*无需做任何处理*/ 20 } 21 var str = args[1]; 22 args = str.split("&"); 23 for(var i = 0; i < args.length; i ++) 24 { 25 str = args[i]; 26 var arg = str.split("="); 27 if(arg.length <= 1) continue; 28 if(arg[0] == sArgName) 29 retval = arg[1]; 30 } 31 return retval; 32 }
g、对Url中部分内容进行解码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 var thisURL = document.URL; 2 var nFundId = GetArgsFromHref(thisURL,"nFundId"); 3 // 字符串,需要进行解码 4 var strFundName = decodeURIComponent(GetArgsFromHref(thisURL,"strFundName"));
h、可编辑表格+jQuery
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $('#bodyRelationTable').bootstrapTable({ 2 //数据来源的网址(示例为本地json数据) 3 url:'./local-data/fundParam.json', 4 searchAlign: 'right', 5 method: 'get', 6 editable:true,//开启编辑模式 7 clickToSelect: true, 8 showPaginationSwitch:true, //显示分页切换按钮 9 search: true, //显示检索框 10 showRefresh: true, //显示刷新按钮 11 showToggle:true, //显示切换按钮来切换列表/卡片视图 12 pagination: true, 13 pageList: [5,15,25,50,100], 14 pageSize:5, 15 pageNumber:1, 16 columns: [ 17 {field:'state', checkbox: true }, 18 {field:'index',edit:false,title:'序号', 19 formatter: function (value, row, index) { 20 return index+1; 21 } 22 }, 23 {field:'id',edit:true,title:'编号',align:'center'}, 24 { 25 field:'version', 26 title: '版本', 27 editable: { 28 type: 'text', 29 title: '版本', 30 validate: function (value) { 31 if ($.trim(value) == '') { 32 return '版本不能为空!'; 33 } 34 } 35 },edit:true 36 }, 37 { 38 field:'key', 39 title: '键', 40 editable: { 41 type: 'text', 42 title: '键', 43 validate: function (value) { 44 if ($.trim(value) == '') { 45 return '键不能为空!'; 46 } 47 } 48 },edit:true 49 }, 50 { 51 field:'value', 52 title: '值', 53 editable: { 54 type: 'text', 55 title: '值', 56 validate: function (value) { 57 if ($.trim(value) == '') { 58 return '姓名不能为空!'; 59 } 60 } 61 },edit:true 62 } 63 ], 64 onEditableSave: function (field, row, oldValue, $el) { 65 $.ajax({ 66 type: "post", 67 url: "/edit", 68 data: {strJson: JSON.stringify(row)}, 69 success: function (data, status) { 70 if (status == "success") { 71 alert("编辑成功"); 72 } 73 }, 74 error: function () { 75 alert("编辑失败"); 76 }, 77 complete: function () { 78 79 } 80 81 }); 82 } 83 }); 84 $('#addPageRowbtn').click(function(){ 85 var data = {}; 86 $('#pageTable').bootstrapTable('append',data); 87 }); 88 89 // $('savePage').onClickCell(function(){ 90 // }); 91 }
i、bootstrapTable 双击事件绑定
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 onDblClickRow: function (row) { 2 console.log("click:" + row.value); 3 // *** 4 },
j、bootstrapTable 表格,“添加”行,事件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $('#addFundInfoRowbtn').unbind('click').click(function () { 2 // 示例 3 var data = {"id": 0,"key":"","value": "","version" : "100"}; 4 $('#fundInfoTable').bootstrapTable('prepend', data); 5 });
k、bootstrapTable 表格,“删除”行,事件
删除行,一般有两种方式:
a.删除页面数据行,整体同步到数据表;
b.传入删除行的ID到后台,删除数据源,后台删除成功后,把剩余数据重新加载到页面。(本文采用此方法)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 $('#delFundInfoRowbtn').unbind('click').click(function () { 2 var rows = $('#fundInfoTable').bootstrapTable('getSelections'); 3 var optFund = "FundInfo"; 4 // (1)调用公共删除方法;(2)执行完成后,回调刷新 5 publicDelRow.delRow(rows,optFund,freshHandler); 6 });
2、后端(Spring MVC)
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.cdoframework.cdolib.data.cdo.CDO; import com.dafy.apollo.admin.domain.gateway.GatewayVO; import com.dafy.apollo.admin.mode.Result; import com.dafy.apollo.admin.service.GatewayService; import com.dafy.apollo.admin.service.TableService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.*; /** * @Author: BGStone * @Description: 网关 Controller * @Date: Create in 15:10 2018/7/20 * @Modified By: */ @Slf4j @Controller @RequestMapping("/gateway") public class GatewayController { @Autowired private GatewayService gatewayService; public static int nFundId_First = 0; @RequestMapping("/init") public ModelAndView init(@RequestParam(defaultValue = "0") int nFundId, ModelAndView mav) { mav.addObject("gatewayVO", gatewayService.getGateway()); mav.setViewName("gateway"); return mav; } @RequestMapping("FundInfo/updateOpenClose.cdo/{strOpenCloseFieldName}/{nOpenCloseState}") @ResponseBody public String updateOpenClose(@PathVariable String strOpenCloseFieldName, @PathVariable int nOpenCloseState) { Map<String,Object> map = new HashMap<>(); map.put("strOpenCloseFieldName",strOpenCloseFieldName); map.put("nOpenCloseState",nOpenCloseState); Result result = TableService.updateFund("Apollo","strTableName", map); if(result.isOK()) { return "success"; } log.info("FundInfo/updateOpenClose.cdo/"+strOpenCloseFieldName+"/"+nOpenCloseState+".requestResult=success" ); return "error"; } /** FundAccountInfo ——<<<< **/ @RequestMapping("FundAccountInfo/get.cdo") @ResponseBody public String getFundAccountInfo(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundAccountInfoMaps = gatewayService.getFundAccountInfoMapByFundId(nFundId); String fundAccountInfoJson = this.mapListToJson(fundAccountInfoMaps); log.info("FundAccountInfo/get.cdo?nFundId="+nFundId+".requestResult="+fundAccountInfoJson); return fundAccountInfoJson; } @RequestMapping("FundAccountInfo/del.cdo") @ResponseBody public String delFundAccountInfo(@RequestParam long[] lIds) { return this.delTool(lIds,"tbFundAccountInfo"); } @RequestMapping("FundAccountInfo/update.cdo") @ResponseBody public String updateFundAccountInfo(@RequestParam Map<String,Object> params) { return this.updateTool(params, "tbFundAccountInfo"); } /** FundAccountInfo ——>>>> **/ /** FundInfo ——<<<< **/ @RequestMapping("FundInfo/getFundAll.cdo") @ResponseBody public String getFundAll(){ List<Map<String,Object>> fundInfoMapList = gatewayService.getFundIdAndNameFromFundInfo(); String resultJson = mapListToJson(fundInfoMapList); GatewayVO gatewayVO = gatewayService.getGateway(); System.out.println(gatewayVO.toString()); log.info("查询结果集 resultJson = " + resultJson); return resultJson; } @RequestMapping("FundInfo/getFundInfoSrc.cdo") @ResponseBody public String getFundInfoSrc(@RequestParam(defaultValue = "0") int nFundId){ nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundInfoMaps = gatewayService.getFundInfoByFundId(nFundId); Set<String> keySet = new HashSet<>(); keySet.add("strHttpHead"); keySet.add("strCodeRelation"); keySet.add("strBodyRelation"); keySet.add("strValueRelation"); String fundInfoJson = this.MapToJsonForKeys(fundInfoMaps, keySet); log.info("FundInfo/getFundInfoSrc.cdo?nFundId="+nFundId+".requestResult="+fundInfoJson); return fundInfoJson; } @RequestMapping("FundInfo/get.cdo") @ResponseBody public String getFundInfoByFundId(@RequestParam(defaultValue = "0") int nFundId){ nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundInfoMaps = gatewayService.getFundInfoByFundId(nFundId); String fundInfoJson = this.mapListToJson(fundInfoMaps); log.info("FundInfo/get.cdo?nFundId="+nFundId+".requestResult="+fundInfoJson); return fundInfoJson; } @RequestMapping("FundInfo/getFormat.cdo") @ResponseBody public String getFundInfoByFundIdToFormat(@RequestParam(defaultValue = "0") int nFundId){ nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundInfoMaps = gatewayService.getFundInfoByFundId(nFundId); // String fundParamJson = this.mapListToJson(fundInfoMaps); Set<String> keySet = new HashSet<>(); keySet.add("strHttpHead"); keySet.add("strCodeRelation"); keySet.add("strBodyRelation"); keySet.add("strValueRelation"); Set<String> keyJsonSet = new HashSet<>(); keyJsonSet.add("strHttpHead"); keyJsonSet.add("strCodeRelation"); keyJsonSet.add("strBodyRelation"); keyJsonSet.add("strValueRelation"); keyJsonSet.add("strRequestMessageModel"); keyJsonSet.add("strRequestSendModel"); String fundInfoJson = this.xmlAndHtmlAndJsonFormatHandler(fundInfoMaps, keySet, keyJsonSet); log.info("FundInfo/getFormat.cdo?nFundId="+nFundId+".requestResult="+fundInfoJson); return fundInfoJson; } @RequestMapping("FundInfo/getField.cdo") @ResponseBody public String getFundInfoFieldByIdAndFieldName(Map<String,Object> params){ long lId = (Long)params.get("lId"); String strFieldName = String.valueOf(params.get("strFieldName")); String resultFieldName = gatewayService.getFieldBylIdAndFieldName("tbFundInfo",lId, strFieldName); log.info("FundInfo/getField.cdo?lId="+lId+"strFieldName = "+strFieldName+".requestResult="+resultFieldName); return resultFieldName; } @RequestMapping("FundInfo/getFieldRestStyle.cdo/{lId}/{strFieldName}") @ResponseBody public String getFundInfoFieldByIdAndFieldNameRestStyle(@PathVariable long lId, @PathVariable String strFieldName) { String resultFieldName = gatewayService.getFieldBylIdAndFieldName("tbFundInfo",lId, strFieldName); log.info("FundInfo/getFieldRestStyle.cdo/"+lId+"/"+strFieldName+".requestResult="+resultFieldName); return resultFieldName; } @RequestMapping("FundInfo/getFieldRestStyleXml.cdo/{lId}/{strFieldName}") @ResponseBody public String getFundInfoFieldByIdAndFieldNameRestStyleXml(@PathVariable long lId, @PathVariable String strFieldName) { String resultFieldName = gatewayService.getFieldBylIdAndFieldName("tbFundInfo",lId, strFieldName); resultFieldName = xmlAndHtmlReplace(resultFieldName); log.info("FundInfo/getFieldRestStyleXml.cdo?lId="+lId+"strFieldName = "+strFieldName+".requestResult="+resultFieldName); return resultFieldName; } @RequestMapping("FundInfo/del.cdo") @ResponseBody public String delFundInfo(@RequestParam long[] lIds) { return this.delTool(lIds,"tbFundInfo"); } @RequestMapping("FundInfo/save.cdo") @ResponseBody public String saveFundInfo(@RequestParam Map<String,Object> params) { String strFundId = String.valueOf( params.get("nFundId")); String strFundName = String.valueOf(params.get("strFundName")); int nFundId = 0; if(StringUtils.isNotBlank(strFundId) && !"null".equals(strFundId)) { nFundId = Integer.valueOf(strFundId); } if(nFundId == 0 || StringUtils.isBlank(strFundName) || "null".equals(strFundName)) { return "error"; } List<Map<String,Object>> fundInfoMaps = gatewayService.getFundInfoByFundId(nFundId); if(fundInfoMaps != null && fundInfoMaps.size() > 0) { return "error"; } params.put("strHttpHead",""); params.put("strRequestMessageModel",""); params.put("strRequestSendModel",""); params.put("strCodeRelation",""); params.put("strBodyKey",""); params.put("strBodyRelation",""); params.put("strValueRelation",""); Result result = TableService.saveFund("Apollo","tbFundInfo",params); if(result.isOK()) { return "success"; } return "error"; } @RequestMapping("FundInfo/update.cdo") public String updateFundInfo(@RequestParam Map<String,Object> params) { return this.updateTool(params, "tbFundInfo"); } /** FundInfo ——>>>> **/ /** FundParam ——<<<< **/ @RequestMapping("FundParam/getParamValueById.cdo") @ResponseBody public String getParamValueById(long lId) { // 一般的查询方式 // Map<String,Object> fundParamMaps = gatewayService.getFundParamMapBylId(lId); // Iterator<Map.Entry<String,Object>> it = fundParamMaps.entrySet().iterator(); // while (it.hasNext()) // { // Map.Entry<String,Object> entry = it.next(); // if("strValue".equals(entry.getKey())) // { // return String.valueOf(entry.getValue()); // } // } // 优化、抽象封装后的查询方式 String strValue = gatewayService.getFieldBylIdAndFieldName("tbFundParam",lId, "strValue"); strValue = xmlAndHtmlReplace(strValue); return strValue; } /** * 根据 nFund 查询 FundParam(返回的 JSON 未作处理) * @param nFundId * @return */ @RequestMapping("FundParam/getFundParam.cdo") @ResponseBody public String getFundParamSrc(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundParamMaps = gatewayService.getFundParamMapByFundId(nFundId); String fundParamJson = this.mapListToJson(fundParamMaps); fundParamJson = this.xmlAndHtmlReplace(fundParamJson); log.info("FundParam/getFundParam.cdo?nFundId="+nFundId+".requestResult="+fundParamJson); return fundParamJson; } /** * 根据 nFund 查询 FundParam(返回的 JSON 做过处理) * @param nFundId * @return */ @RequestMapping("FundParam/get.cdo") @ResponseBody public String getFundParam(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundParamMaps = gatewayService.getFundParamMapByFundId(nFundId); Set<String> needFormatSet = new HashSet<>(); needFormatSet.add("strValue"); String fundParamJson = xmlAndHtmlAndJsonFormatHandler(fundParamMaps, needFormatSet, needFormatSet); log.info("FundParam/get.cdo?nFundId="+nFundId+".requestResult="+fundParamJson); return fundParamJson; } @RequestMapping("FundParam/del.cdo") @ResponseBody public String delFundParam(@RequestParam long[] lIds) { return this.delTool(lIds,"tbFundParam"); } @RequestMapping("FundParam/update.cdo") @ResponseBody public String updateFundParam(@RequestParam Map<String,Object> params) { return updateTool(params, "tbFundParam"); } /** FundInfo ——>>>> **/ @RequestMapping("FundRelation/getFundRelation.cdo") @ResponseBody public String getFundRelationSrc(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundRelationMaps = gatewayService.getFundRelationMapByFundId(nFundId); String fundRelationJson = this.mapListToJson(fundRelationMaps); log.info("FundRelation/getFundRelation.cdo?nFundId="+nFundId+".requestResult="+fundRelationJson); return fundRelationJson; } @RequestMapping("FundRelation/getFundRelationXml.cdo/{lId}/{strFieldName}") @ResponseBody public String getFundRelationSrcXml(@PathVariable int lId, @PathVariable String strFieldName) { String resultFieldName = gatewayService.getFieldBylIdAndFieldName("tbFundRelation",lId, strFieldName); resultFieldName = this.xmlAndHtmlReplace(resultFieldName); log.info("FundRelation/getFundRelationXml.cdo/"+lId+"/"+strFieldName+".requestResult="+resultFieldName); return resultFieldName; } @RequestMapping("FundRelation/getFundRelationFormat.cdo") @ResponseBody public String getFundRelationSrcFormat(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundRelationMaps = gatewayService.getFundRelationMapByFundId(nFundId); Set<String> keySet = new HashSet<>(); keySet.add("strRelation"); String fundRelationJson = this.xmlAndHtmlAndJsonFormatHandler(fundRelationMaps, keySet, new HashSet<>()); log.info("FundRelation/getFundRelation.cdo?nFundId="+nFundId+".requestResult="+fundRelationJson); return fundRelationJson; } @RequestMapping("FundRelation/get.cdo") @ResponseBody public String getFundRelation(@RequestParam(defaultValue = "0") int nFundId) { nFundId = this.checkFundId(nFundId); List<Map<String,Object>> fundRelationMaps = gatewayService.getFundRelationMapByFundId(nFundId); Set<String> formatSet = new HashSet<>(); formatSet.add("strRelation"); String fundRelationJson =this.xmlAndHtmlAndJsonFormatHandler(fundRelationMaps, formatSet, formatSet); log.info("FundRelation/get.cdo?nFundId="+nFundId+".requestResult="+fundRelationJson); return fundRelationJson; } @RequestMapping("FundRelation/del.cdo") @ResponseBody public String delFundRelation(@RequestParam long[] lIds) { return this.delTool(lIds,"tbFundRelation"); } @RequestMapping("FundRelation/update.cdo") @ResponseBody public String updateFundRelation(@RequestParam Map<String,Object> params) { return updateTool(params, "tbFundRelation"); } /** * 更新 * @param params * @param strTableName * @return */ private String updateTool(Map<String,Object> params,String strTableName) { Result result = null; Map<String, Object> map = jsonToMap(params); String lId = String.valueOf(map.get("lId")) ; if("0".equals(lId)) { map.remove("lId"); map.remove("state"); result = TableService.saveFund("Apollo",strTableName, map); }else { map.remove("lId"); map.remove("state"); map.put("lId",Long.parseLong(lId)); result = TableService.updateFund("Apollo",strTableName, map); } if(result.isOK()) { return "success"; } return result.getMsg(); } /** * 删除 * @param lIds * @param strTableName * @return */ private String delTool(long[] lIds, String strTableName) { boolean flag = true; List<Long> errorlIds = new ArrayList<>(); for (long lId : lIds) { Result result = TableService.del("Apollo", strTableName, lId); if(!result.isOK()) { flag = false; errorlIds.add(lId); } } if(!flag) { return "部分成功!未能删除的ID为=" + errorlIds.toString(); } return "success"; } /** * 传入 需要转换的 key 集合,将其全部转换 * @param fundMaps 需要转换的数据源 * @param keySets 需要转换的 Key 集合 * @return */ private String MapToJsonForKeys(List<Map<String,Object>> fundMaps, Set<String> keySets) { boolean flag = true; JSONArray jsonArray = new JSONArray(); if(fundMaps != null) { for (Map map : fundMaps) { JSONObject jsonObject = new JSONObject(); Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String,Object> entry = it.next(); String strSrcKey = entry.getKey(); Iterator<String> setIt = keySets.iterator(); while (setIt.hasNext()) { if(setIt.next().equals(strSrcKey)) { String srcXML = entry.getValue().toString(); CDO cdoSrc = CDO.fromXML(srcXML); String srcJSON = cdoSrc.toJSON().toString(); srcJSON = this.cleJSONFormat(srcJSON); jsonObject.put(entry.getKey(),srcJSON); flag = false; continue; } } if (flag) { jsonObject.put(entry.getKey(),entry.getValue()); } flag = true; } jsonArray.add(jsonObject); } } return jsonArray.toJSONString(); } /** * 验证 资金方Id * @param nFundId * @return */ private int checkFundId(int nFundId) { if (nFundId == 0 && nFundId_First != 0) { nFundId = nFundId_First; }else if(nFundId ==0) { List<Map<String,Object>> fundInfoMaps = gatewayService.getFundIdAndNameFromFundInfo(); if(fundInfoMaps != null && fundInfoMaps.size() > 0) { Map<String, Object> map = fundInfoMaps.get(0); nFundId = (Integer) map.get("nFundId"); } } return nFundId; } /** * MapList to JSON * @param mapList * @return */ private String mapListToJson(List<Map<String,Object>> mapList) { JSONArray jsonArray = new JSONArray(); if(mapList != null) { for (Map map : mapList) { JSONObject jsonObject = new JSONObject(); Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String,Object> entry = it.next(); jsonObject.put(entry.getKey(),entry.getValue()); } jsonArray.add(jsonObject); } } return jsonArray.toJSONString(); } /** * 将 Map 中的 JSON 数据转换为 Map * @param params * Key : strJson * value : JSON 数据 * @return */ private Map<String,Object> jsonToMap(Map<String,Object> params) { try { String strJSON = (String) params.get("strJson"); JSONObject myJson = JSONObject.parseObject(strJSON); return myJson; } catch (Exception e) { e.printStackTrace(); log.info("jsonToMap 异常" + e.getMessage()); } return null; } /** * 清楚 JSON 格式(便于前端显示) * @param strJson * @return */ private String cleJSONFormat(String strJson) { strJson = strJson.replace("\\\"","\""); strJson = strJson.replace("\"","'"); String plId = "'lId'"; String pFundId = "'nFundId'"; String pKey = "'strKey':'"; String pValue = "','strValue':'"; String pE = "'},"; String pV = "'}]"; String alId = "\"lId\""; String aFundId = "\"nFundId\""; String aKey = "\"strKey\":\""; String aValue = "\",\"strValue\":\""; String aE = "\"},"; String aV = "\"}]"; strJson = strJson.replace(plId, alId); strJson = strJson.replace(pFundId, aFundId); strJson = strJson.replace(pKey, aKey); strJson = strJson.replace(pValue, aValue); strJson = strJson.replace(pE, aE); strJson = strJson.replace(pV, aV); strJson = strJson.replace("'", ""); return strJson; } /** * 为 xml 和 html 添加 <xmp></xmp> 文本化,Json 格式化数据 * @param fundMaps * @param keyXmlAndHtmlSets * @param keyJsonSets * @return */ private String xmlAndHtmlAndJsonFormatHandler(List<Map<String,Object>> fundMaps, Set<String> keyXmlAndHtmlSets, Set<String> keyJsonSets) { boolean flag = true; JSONArray jsonArray = new JSONArray(); if(fundMaps != null) { for (Map map : fundMaps) { JSONObject jsonObject = new JSONObject(); Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String,Object> entry = it.next(); String strSrcKey = entry.getKey(); // 处理 Xml 和 html 两种格式数据 Iterator<String> setXmlAndHtmlIt = keyXmlAndHtmlSets.iterator(); while (setXmlAndHtmlIt.hasNext()) { if(setXmlAndHtmlIt.next().equals(strSrcKey)) { String strSrc = entry.getValue().toString(); // StringUtils.isNot if(StringUtils.isBlank(strSrc)) { jsonObject.put(entry.getKey(),""); } strSrc = xmlAndHtmlReplace(strSrc); // strSrc = strSrc.replace("\"", "'"); // String strResult = "<xmp>" + strSrc + "</xmp>"; jsonObject.put(strSrcKey,strSrc); flag = false; continue; } } // 处理 Json 格式数据 Iterator<String> setJsonIt = keyJsonSets.iterator(); while (setJsonIt.hasNext()) { if(setJsonIt.next().equals(strSrcKey)) { String strSrc = entry.getValue().toString(); if(StringUtils.isBlank(strSrc)) { jsonObject.put(entry.getKey(),""); } strSrc = cleJSONFormat(strSrc); jsonObject.put(strSrcKey,strSrc); flag = false; continue; } } if(flag) { jsonObject.put(strSrcKey,entry.getValue()); } flag = true; } jsonArray.add(jsonObject); } } return jsonArray.toJSONString(); } private String xmlAndHtmlReplace(String strSrc) { // strSrc = strSrc.replace("\"", "\\\""); // strSrc = strSrc.replace("\"", "\\\""); String pPHtml = "<html>"; String pEHtml = "</html>"; String pXmlCDO = "^.*?(<?xml )"; String pECDO = "(?<=(</CDO))[^(</CDO)((s]+(?=[^(</CDO)]*$)"; String aPHtml = "<xmp><html>"; String aEHtml = "</html></xmp>"; String aPXmlCDO = "<xmp><?xml "; String aECDO = "></xmp>"; strSrc = strSrc.replace(pPHtml, aPHtml); strSrc = strSrc.replace(pEHtml, aEHtml); strSrc = strSrc.replaceFirst(pXmlCDO, aPXmlCDO); strSrc = strSrc.replaceAll(pECDO, aECDO); return strSrc; } }
三、Service 实现
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.cdoframework.cdolib.data.cdo.CDO; import com.dafy.apollo.admin.db.SpringRunner; import com.dafy.apollo.admin.domain.gateway.*; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @Service @Slf4j public class GatewayService { public GatewayVO getGateway(){ GatewayVO gatewayVO = new GatewayVO(); // 1.获取 资金方名称列表 List<Map<String,Object>> fundInfoList = this.getFundIdAndNameFromFundInfo(); gatewayVO.setFundNameS(mapListToMap(fundInfoList)); // 2.获取 资金方信息列表 List<FundInfo> fundInfoS = this.findFundInfoListByFundId(0); gatewayVO.setFundInfoS(fundInfoS); // 3.获取 资金方账单列表 List<FundAccountInfo> fundAccountInfoS = this.findFundAccountInfoByFundId(0); gatewayVO.setFundAccountInfoS(fundAccountInfoS); // 4.获取 资金方参数列表 List<FundParam> fundParamS = this.findFundParamByFundId(0); gatewayVO.setFundParamS(fundParamS); // 5.获取 资金方关系列表 List<FundRelation> fundRelationS = this.findFundRelationByFundId(0); gatewayVO.setFundRelationS(fundRelationS); return gatewayVO; } /** * MapList to Map * 将 MapList 中的 key:nFundId、strFundName,value为相应的值; * 转到一个 map 中,key:为 nFundId 相应的值,value 为 strFundName 相应的值。 * @param mapList * @return */ private Map mapListToMap(List<Map<String,Object>> mapList) { Map resultMap = new HashMap(mapList.size()); if(mapList != null) { for (Map map : mapList) { resultMap.put(map.get("nFundId"),map.get("strFundName")); } } return resultMap; } /** * MapList to JSON * @param mapList * @return */ private String mapListToJson(List<Map<String,Object>> mapList) { JSONArray jsonArray = new JSONArray(); if(mapList != null) { for (Map map : mapList) { JSONObject jsonObject = new JSONObject(); Iterator<Map.Entry<String,Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String,Object> entry = it.next(); jsonObject.put(entry.getKey(),entry.getValue()); } jsonArray.add(jsonObject); } } return jsonArray.toJSONString(); } public List<GatewayDomain> getListBy(int borrowMode,long lApolloId,long nodeId) { List<GatewayDomain> resultList = Lists.newArrayList(); // String getIdSql = "SELECT id FROM tbApolloData WHERE strTraceId = '" + traceId + "' type = " + type; // Long id = SpringRunner.getInstance().getReadJdbcTemplate(borrowMode).queryForObject(getIdSql,Long.class); String sql = "SELECT * FROM tbApolloGatewayRecord WHERE lApolloId = ? AND lNodeId = ?"; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate(borrowMode).queryForList(sql,lApolloId,nodeId); if(list != null && list.size() > 0){ for (Map<String,Object> map : list){ GatewayDomain domain = new GatewayDomain(); domain.setId((Long) map.get("lId")); domain.setBorrowMode((Integer) map.get("nFundId")); domain.setSn((String) map.get("strSN")); domain.setApolloId(lApolloId); domain.setNodeId(nodeId); domain.setRequestDatagram((String) map.get("strRequestData")); domain.setResponseDatagram((String) map.get("strResponseData")); domain.setRequestTime(map.get("dtCreateTime").toString()); resultList.add(domain); } } return resultList; } /** * 获取 资金方列表 * @return */ public List<FundParam> getFundList() { log.info("获取 资金方列表——<<<<"); List<FundParam> resultList = Lists.newArrayList(); String sql = "SELECT nFundId,strFundName FROM tbFundParam GROUP BY nFundId"; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql); if(list != null && list.size() > 0){ for (Map<String,Object> map : list){ FundParam domain = new FundParam(); domain.setNFundId((Integer) map.get("nFundId")); domain.setStrFundName((String) map.get("strFundName")); resultList.add(domain); } } log.info("获取 资金方列表——>>>>,长度为:"+resultList.size()); return resultList; } /** * 根据 资金方ID 查询 资金方信息列表 List<FundInfo> * @param nFundId * @return */ public List<FundInfo> getFundInfoListByFundId(int nFundId) { List<FundInfo> resultList = Lists.newArrayList(); String sql = "SELECT * FROM tbFundInfo WHERE nFundId = ?"; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,nFundId); if(list != null && list.size() > 0){ for (Map<String,Object> map : list){ FundInfo fundInfo = new FundInfo(); fundInfo.setLId((Long) map.get("lId")); fundInfo.setNFundId((Integer) map.get("nFundId")); fundInfo.setBTransfer((Boolean)map.get("nTransfer")); fundInfo.setStrAfterFilter((String)map.get("strAfterFilter")); fundInfo.setStrBeforeFilter((String)map.get("strBeforeFilter")); fundInfo.setStrBodyKey((String) map.get("strBodyKey")); fundInfo.setStrBodyRelation((String) map.get("strBodyRelation")); fundInfo.setStrCodeKey((String)map.get("strCodeKey")); fundInfo.setStrCodeRelation((String)map.get("strCodeRelation")); fundInfo.setStrFunctionName((String)map.get("strFunctionName")); fundInfo.setStrHttpHead((String)map.get("strHttpHead")); fundInfo.setStrMessageStructure((String)map.get("strMessageStructure")); fundInfo.setStrMsgKey((String)map.get("strMsgKey")); fundInfo.setStrRequestMessageModel((String)map.get("strRequestMessageModel")); fundInfo.setStrRequestSendModel((String)map.get("strRequestSendModel")); fundInfo.setStrSendMethodName((String)map.get("strSendMethodName")); fundInfo.setStrTransferPath((String)map.get("strTransferPath")); fundInfo.setStrUrl((String)map.get("strUrl")); fundInfo.setStrUrlKey((String)map.get("strUrlKey")); fundInfo.setStrValueRelation((String)map.get("strValueRelation")); resultList.add(fundInfo); } } return resultList; } /** * 根据 资金方ID 查询 资金方信息列表 * @return */ public List<Map<String,Object>> getFundIdAndNameFromFundInfo() { String sql = " SELECT nFundId,strFundName FROM tbFundInfo GROUP BY nFundId,strFundName "; return SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql); } /** * 根据 资金方Id 查询 FundInfo Map集合 * @param nFundId * @return */ public List<Map<String,Object>> getFundInfoByFundId(int nFundId) { String sql = " SELECT * FROM tbFundInfo WHERE nFundId = ? ORDER BY lId DESC "; return SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql, nFundId); } /** * 根据 资金方Id 查询 FundInfo Map集合 * @param nFundId * @return */ public List<FundInfo> findFundInfoListByFundId(int nFundId) { String sql = " SELECT * FROM tbFundInfo WHERE nFundId = ? ORDER BY lId DESC "; return SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,FundInfo.class, nFundId); } /** * 根据 资金方Id,字段Key,查询 FundInfo 字段信息 * @param lId * @param strFieldName * @return */ public List<Map<String,Object>> getFundInfoFieldByIdAndFieldName(int lId,String strFieldName) { String sql = " SELECT " + strFieldName +" FROM tbFundInfo WHERE lId = ?"; return SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql, lId); } /** * 根据 ID 查询 字段 BodyRelation * @param lId * @return */ public String getBodyRelationByFundInfoId(int lId) { List<FundInfo> resultList = Lists.newArrayList(); String sql = "SELECT strBodyRelation FROM tbFundInfo WHERE lId = ?"; String strBodyRelationXML = SpringRunner.getInstance().getReadJdbcTemplate().queryForObject(sql,String.class,lId); CDO cdoBodyRelation = CDO.fromXML(strBodyRelationXML); return cdoBodyRelation.toJSON(); } public List<FundAccountInfo> getFundAccountInfoByFundId(int nFundId) { List<FundAccountInfo> resultList = Lists.newArrayList(); String sql = "SELECT * FROM tbFundAccountInfo WHERE nFundId = ?"; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,nFundId); if(list != null && list.size() > 0){ for (Map<String,Object> map : list){ FundAccountInfo fundAccountInfo = new FundAccountInfo(); fundAccountInfo.setLId((Long) map.get("lId")); fundAccountInfo.setNFundId((Integer) map.get("nFundId")); fundAccountInfo.setNType((Integer) map.get("nType")); fundAccountInfo.setNSend((Integer) map.get("nSend")); fundAccountInfo.setStrFunctionName((String)map.get("strFunctionName")); fundAccountInfo.setStrKeyRelation((String)map.get("strKeyRelation")); fundAccountInfo.setStrCloseUrl((String)map.get("strCloseUrl")); fundAccountInfo.setStrTitle((String)map.get("strTitle")); resultList.add(fundAccountInfo); } } return resultList; } /** * 根据资金方ID 查询 FundAccountInfo * @param nFundId * @return */ public List<Map<String,Object>> getFundAccountInfoMapByFundId(int nFundId) { String sql = "SELECT * FROM tbFundAccountInfo WHERE nFundId = ? ORDER BY lId DESC "; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,nFundId); return list; } /** * 根据资金方ID 查询 FundAccountInfo * @param nFundId * @return */ public List<FundAccountInfo> findFundAccountInfoByFundId(int nFundId) { String sql = "SELECT * FROM tbFundAccountInfo WHERE nFundId = ? ORDER BY lId DESC "; return SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,FundAccountInfo.class,nFundId); } /** * 根据资金方ID 查询 FundParam * @param nFundId * @return */ public List<FundParam> findFundParamByFundId(int nFundId) { String sql = "SELECT * FROM tbFundParam WHERE nFundId = ? ORDER BY lId DESC "; List<FundParam> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,FundParam.class,nFundId); return list; } /** * 根据资金方ID 查询 FundParam * @param nFundId * @return */ public List<Map<String,Object>> getFundParamMapByFundId(int nFundId) { String sql = "SELECT * FROM tbFundParam WHERE nFundId = ? ORDER BY lId DESC "; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,nFundId); return list; } /** * 根据资金方ID 查询 FundParam * @param lId * @return */ public Map<String,Object> getFundParamMapBylId(long lId) { String sql = "SELECT * FROM tbFundParam WHERE lId = ? "; Map<String,Object> map = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,lId).get(0); return map; } /** * 根据资金方ID 查询 FundParam * @param lId * @return */ public String getFieldBylIdAndFieldName(String tableName, long lId, String fieldName) { String sql = "SELECT "+ fieldName +" FROM "+ tableName +" WHERE lId = " + lId; String resultFieldName = SpringRunner.getInstance().getReadJdbcTemplate().queryForObject(sql,String.class); return resultFieldName; } /** * 根据资金方ID 查询 FundRelation * @param nFundId * @return */ public List<FundRelation> findFundRelationByFundId(int nFundId) { String sql = "SELECT * FROM tbFundRelation WHERE nFundId = ? ORDER BY lId DESC "; List<FundRelation> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,FundRelation.class,nFundId); return list; } /** * 根据资金方ID 查询 FundRelation * @param nFundId * @return */ public List<Map<String,Object>> getFundRelationMapByFundId(int nFundId) { String sql = "SELECT * FROM tbFundRelation WHERE nFundId = ? ORDER BY lId DESC "; List<Map<String,Object>> list = SpringRunner.getInstance().getReadJdbcTemplate().queryForList(sql,nFundId); return list; } }