我们在开发前端项目时，一般会对用户敏感信息（如姓名、手机号码、身份证号码）进行脱敏处理。本文以手机号码脱敏处理为例进行说明。如 13366668888 脱敏处理后变成 133****8888。具体处理方法如下：/**手机号码脱敏处理 * @method phoneDesensitization * @param {String} phone 需要处理的手机号码 * @param {String} char 脱敏替换的字符 * @return {String} 脱敏处理后的手机号码 */ function phoneDesensitization(phone, char) { return phone.replace(/(\d{3})\d*(\d{4})/, `$1${new Array(5).join(char)}$2`) }需要调用的地方直接调用：console.info(phoneDesensitization('13366668888', '*')) // => 133****8888 console.info(phoneDesensitization('13366668888', '密')) // => 133密密密密8888说明：这里主要使用了正则表达式的 分组 和 $1,$2 的方法。通过 () 对字符串进行分组，$相当于下标从1开始的集合，$n相当于对应第n个索引的值。/(\d{3})\d*(\d{4})/ 相当于把字符串前3个和后4个字符分为两个集合，$1${new Array(5).join(char)}$2 相当于保留前3后4的字符后，替换剩下字符串为新字符串 new Array(5).join(char)。
on() 和 click() 的区别:二者在绑定静态控件时没有区别，但是如果面对动态产生的控件，只有 on() 能成功的绑定到动态控件中。以下实例中原先的 HTML 元素点击其身后的 Delete 按钮就会被删除。而动态添加的 HTML 元素，使用 click() 这种写法，点击 Delete 按钮无法删除；使用 On() 方式可以。HTML 展示jQuery中on()和click()的区别 点击生成新按钮。NewOn生成的Delete按钮行为用on()实现，NewClick生成的Delete按钮行为用click()实现。 NewOn NewClick 原先的HTML元素on Delete 原先的HTML元素click Delete JS$("#newclick").click(function(){ $(".li").append(' 动态添加的HTML元素click Delete '); }); $("#newon").click(function(){ $(".li").append(' 动态添加的HTML元素on Delete '); }); $(".delete").click(function(){ $(this).parent().remove(); }); $(".li").on('click', ".deleteon", function(){ $(this).parent().remove(); }) $(".deleteclick").click(function(){ $(this).parent().remove(); });
1.1数据结构的基本概念数据结构：是相互之间存在一种或多种特定关系的数据元素的集合。数据对象：是具有相同性质的数据元素的集合，是数据的一个子集。数据结构的三要素：逻辑结构，物理结构（存储结构），数据的运算逻辑结构：集合，线性结构，树形结构，网状结构物理结构（存储结构）（会影响数据运算速度）：顺序存储（物理相邻连续的），链式存储（指针），索引存储（索引表），散列存储（哈希存储）数据的运算：施加在数据上的运算包括运算的定义和实现。运算的定义是针对逻辑机构的，指出运算的功能；运算的实现是针对存储结构的，指出运算的具体操作步骤。数据类型数据类型是一个值的集合和定义在此集合上的一组操作总称。原子类型。其值不可再分的数据类型结构类型。其值可以再分解为若干成分（分量）的数据类型抽象数据类型（ADT）是抽象数据组织及与之相关的操作。1.2.1算法的基本概念程序 = 数据结构 + 算法算法必须具备的特性有穷性：一个算法必须总在执行有穷步之后结束，且每一步都可在有穷时间内完成。注：算法必须是有穷的，而程序可以是无穷的确定性：算法中每条指令必须有确切的含义，对于相同的输入只能的书相同的输出。可行性：算法中描述的操作都可以通过已经实现的基本运算执行有限次来实现。输入：一个算法有零个或多个输入，这些输入取自于莫格特定的对象的集合。输出:一个算法有一个或多个输出，这些输出是与输入有着某种特定关系的量。”好“算法的特质正确性。算法应能正确的解决求解问题。可读性。算法应具有良好的可读性，以帮助人们理解。健壮性。输入非法数据时，算法能适当的做出反应或进行处理，而不会产生莫名其妙的输出结果。高效率与低存储量需求。执行速度快，时间复杂度低。不费内存，空间复杂度低。
修改Tomcat的server.xml文件，在Connector中加一句<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>完整的xml文件<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <Server port="8005" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.startup.VersionLoggerListener"/> <!-- Security listener. Documentation at /docs/config/listeners.html <Listener className="org.apache.catalina.security.SecurityListener" /> --> <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/> <Listener className="org.apache.catalina.core.JasperListener"/> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/> <GlobalNamingResources> <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/> </GlobalNamingResources> <Service name="Catalina"> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/> <!-- <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> --> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/> <!-- You should set jvmRoute to support load-balancing via AJP ie : <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> --> <Engine defaultHost="localhost" name="Catalina"> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <Realm className="org.apache.catalina.realm.LockOutRealm"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log." suffix=".txt"/> <Context crossContext="true" docBase="G:/www/tomcat/hcfimages" path="/GoldenControl_content" reloadable="false"/> <Context docBase="GoldenShield" path="/GoldenControl" reloadable="true" source="org.eclipse.jst.jee.server:GoldenShield"/></Host> </Engine> </Service> </Server>
导出功能1、Jsp(一个按钮) 导出 2、Js$("#export").click(function(){ window.location.href =path+"/gc/riskBadAssets/exportExcel?filter=" + encodeURIComponent(JSON.stringify(filter)); });3、Controllerpackage com.ctbr.applet.controller.manage; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ctbr.applet.service.IMpRewardListService; import com.ctbr.baseFrame.core.BaseController; import com.ctbr.baseFrame.model.AjaxResult; import com.ctbr.baseFrame.model.PageResult; import com.ctbr.baseFrame.service.IExcelService; import com.ctbr.baseFrame.util.UserContext; import net.sf.json.JSONArray; /** * 业绩管理 */ @Controller @RequestMapping(value = "/appletManage/mpReward") public class MpRewardListController extends BaseController { private static Logger logger = Logger.getLogger(MpRewardListController.class); @Resource private IMpRewardListService service; @ResponseBody @RequestMapping(value="/exportExcel") public void exportExcel(HttpServletResponse response,HttpServletRequest request){ String filter = request.getParameter("filter"); Map<String,Object> map = new HashMap<String,Object>(); String vague = null; try { if(getFilter(JSONArray.fromObject(filter)) == null || getFilter(JSONArray.fromObject(filter)).equals("")) { vague = getFilter(JSONArray.fromObject(filter)); } else { vague = new String(getFilter(JSONArray.fromObject(filter)).getBytes("ISO8859-1"), "UTF-8"); } } catch (Exception e) { logger.info("根据模糊匹配时导出excel表格时发生异常", e); } map.put("filter", vague); String titleList[] = {"奖励明细编号" , "业务编号" , "客户名称" , "业务日期" , "发生时间" , "业务金额" , "原始奖励金额" , "实际奖励金额" , "奖励来源" , "奖励规则描述" , "代理人名称" , "状态" , "审核人", "审核时间" }; String dataListKey[] = {"bsn_id" , "loan_id" , "customer_name" , "bsn_date" , "generate_date" , "bsn_amount" , "origin_amount" , "act_amount" , "reward_origin_nm" , "reward_desc" , "agent_nm" , "status_flag_nm" , "audit_user", "audit_date" }; List<Map<String,Object>> dataList = service.getRewardListExcelData(map); excelService.exportExcel("奖励列表", "奖励列表", titleList, dataListKey, dataList, response); } }4、IMpRewardListServicepackage com.ctbr.applet.service; import java.util.List; import java.util.Map; import com.ctbr.baseFrame.core.IBaseService; public interface IMpRewardListService extends IBaseService { /**业绩管理导出excel所需数据 * */ public List<Map<String, Object>> getRewardListExcelData(Map<String, Object> paramsMap); } 5、MpRewardListServiceImplpackage com.ctbr.applet.service.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ctbr.applet.service.IMpRewardListService; import com.ctbr.baseFrame.core.AbstractBaseService; @Service("mpRewardListService") @Transactional public class MpRewardListServiceImpl extends AbstractBaseService implements IMpRewardListService { /**操作对应的表 * */ @Override public String getTableMapping() { return "mp_reward_list"; } /**建立列表导出 * */ @Override public List<Map<String, Object>> getRewardListExcelData(Map<String, Object> paramsMap) { List<Map<String, Object>> data = this.baseDao.selectList("mp_reward_list.selectRewardExcel", paramsMap); return data; } } 6、IExcelServicepackage com.ctbr.baseFrame.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; public interface IExcelService { /** * 导出Excel * @Title: exportExcel * @Description: TODO(这里用一句话描述这个方法的作用) * @param: @param workName 工作簿名称 * @param: @param sheetName sheeet名称 * @param: @param titleList 列名集合 * @param: @param dataListKey 数据集合key * @param: @param dataList 数据 * @param: @param response HttpServletResponse * @return: void * @throws */ public void exportExcel(String workName, String sheetName, String[] titleList, String[] dataListKey, List<Map<String,Object>> dataList, String[] foamatTitle,HttpServletResponse response); }7、IExcelServiceImplpackage com.ctbr.baseFrame.service.impl; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigDecimal; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.stereotype.Service; import com.ctbr.baseFrame.service.IExcelExportService; import com.ctbr.baseFrame.util.StringUtil; import com.ctbr.baseFrame.util.TimestampTool; @Service public class ExcelExportServiceImpl implements IExcelExportService { //日期 private String p1 ="^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$"; //日期：时间 // private String p2 = "^(\\d{2}|\\d{4})(?:\\-)?([0]{1}\\d{1}|[1]{1}[0-2]{1})(?:\\-)?([0-2]{1}\\d{1}|[3]{1}[0-1]{1})(?:\\s)?([0-1]{1}\\d{1}|[2]{1}[0-3]{1})(?::)?([0-5]{1}\\d{1})(?::)?([0-5]{1}\\d{1})$"; //千位分割 private String p3 ="^((-?[1-9][0-9]{0,2}(,\\d{3})*)|0)(\\.\\d{1,2})?$"; //数字 private String p4 ="^(-?\\d+)(\\.\\d+)?$"; private CellStyle cellStyleDate = null; private CellStyle cellStyleBigDecimal = null; private List<Integer> formatIndexList = null; /** * 不需要格式化的title(字符串转日期、字符串转数值) * @param titleList */ public void initFormatIndexList(String[] titleList,String[] foamatTitle) { formatIndexList = new ArrayList<Integer>(); List<String> titleListTemp = Arrays.asList(titleList); if(foamatTitle != null && foamatTitle.length > 0) { for(String title : foamatTitle) { formatIndexList.add(titleListTemp.indexOf(title)); } } } @Override public synchronized void exportExcel(String workName, String sheetName, String[] titleList, String[] dataListKey, List<Map<String, Object>> dataList, String[] foamatTitle,HttpServletResponse response) { initFormatIndexList(titleList,foamatTitle); cellStyleDate = null; cellStyleBigDecimal = null; Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(sheetName); int idx = 0; if (titleList != null && titleList.length > 0) {//设置标题 idx = 1; Row row = sheet.createRow((short)0); row.setHeightInPoints((short) 20); int j = 0; //设置字体 Font font = wb.createFont(); font.setFontHeightInPoints((short) 12); //字体高度 font.setColor(HSSFColor.WHITE.index); //字体颜色 font.setFontName("黑体"); //字体 font.setBold(true); //设置样式 CellStyle cellStyle = wb.createCellStyle(); cellStyle.setFont(font); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); cellStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); cellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); for (String title : titleList) { creatCell(wb, row, j++, title, cellStyle); } } if (dataList != null && !dataList.isEmpty()) {//设置数据 for (int i = 0; i < dataList.size(); i++) { Map<String, Object> data = dataList.get(i); Row row = sheet.createRow(i + idx); if (dataListKey != null && dataListKey.length > 0) {//存在KEY for (int j = 0; j < dataListKey.length; j++) { creatCell(wb, row, j, data.get(dataListKey[j]), null); } } else {//不存在KEY Set<Entry<String, Object>> set = data.entrySet(); Iterator<Entry<String, Object>> it = set.iterator(); int j = 0; while (it.hasNext()) { Entry<String, Object> entry = it.next(); creatCell(wb, row, j++, entry.getValue(), null); } } } } if (sheet.getRow(0) != null) { for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i ++) {//自动调整列宽 sheet.autoSizeColumn(i); } } try { //输出excel response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(workName + ".xls", "UTF-8")); ServletOutputStream out = response.getOutputStream(); wb.write(out); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * excel单元格日期格式 * @param workbook * @return */ public CellStyle getCellStyleByDate(Workbook workbook) { if(cellStyleDate == null) { cellStyleDate = workbook.createCellStyle(); CreationHelper createHelper = workbook.getCreationHelper(); short dateFormat = createHelper.createDataFormat().getFormat("yyyy/MM/dd"); cellStyleDate.setDataFormat(dateFormat); return cellStyleDate; }else { return cellStyleDate; } } /** * excel单元格千位分割格式 * @param workbook * @return */ public CellStyle getCellStyleByBigDecimal(Workbook workbook) { if(cellStyleBigDecimal == null) { cellStyleBigDecimal = workbook.createCellStyle(); cellStyleBigDecimal.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); return cellStyleBigDecimal; }else { return cellStyleBigDecimal; } } /** * 创建单行 * @Title: creatCell * @Description: TODO(这里用一句话描述这个方法的作用) * @param: @param row * @param: @param idx * @param: @param val * @return: void * @throws */ private void creatCell(Workbook workbook,Row row, int idx, Object val, CellStyle style) { Cell cell = row.createCell(idx); if (val instanceof String) { if(formatIndexList != null && formatIndexList.size() > 0 && formatIndexList.contains(idx)) { if(Pattern.matches(p1, (String)val)){//如果是日期格式的字符 cell.setCellValue(TimestampTool.parseDate((String)val)); cell.setCellStyle(getCellStyleByDate(workbook)); }else if(Pattern.matches(p3, (String)val) || Pattern.matches(p4, (String)val)){//如果是千位分割格式的字符 try { cell.setCellValue(new DecimalFormat().parse((String)val).doubleValue()); } catch (ParseException e) { e.printStackTrace(); } cell.setCellStyle(getCellStyleByBigDecimal(workbook)); }else { cell.setCellValue((String)val); } }else { cell.setCellValue((String)val); } } else if (val instanceof Integer) { cell.setCellValue((Integer)val); } else if (val instanceof Long) { cell.setCellValue((Long)val); } else if (val instanceof Date) { cell.setCellValue((Date)val); } else if (val instanceof BigDecimal) { cell.setCellValue(new BigDecimal(StringUtil.isNull(val)).doubleValue()); } else if (val instanceof Double) { cell.setCellValue((Double)val); } else { cell.setCellValue((String)val); } if (style != null) { cell.setCellStyle(style); } } }导入功能1、Js$("#file_uploadBtn").click(function() { if(!$("#uploadForm").validate().form()){ return false; } // if(!$('#file').get(0).files[0]){ // ie9不支持files属性 if($('#file').get(0).value === ""){ $.zkbr.alert("提示信息","请选择上传文件"); return false; } $("#file_uploadBtn").prop("disabled",true); var data = $("#uploadForm").serializeObject(); data.collateralId = $("#collateralId").val(); $.ajaxFileUpload({ url : path+"/base/migration/upload", type: "post", secureuri : false,//一般设置为false data: data, fileElementId : "file",//文件上传控件的id属性 dataType : "json",//返回值类型 一般设置为json success : function(data) {//服务器成功响应处理函数 $("#file_uploadBtn").prop("disabled",false); loadFile(); if(data.statusCode=='505'){ $.zkbr.alert("提示",data.errorMsg); }else{ $("#uploadModal").modal('hide'); $.zkbr.alert("提示","数据导入成功"); } //location.reload(); } }); });2、Servicepackage com.ctbr.base.service; import org.springframework.web.multipart.MultipartFile; import com.ctbr.baseFrame.core.IBaseService; import com.ctbr.baseFrame.model.AjaxResult; public interface IHistoryDateMigrationService extends IBaseService { /** * TODO(导入客户信息) * @param file excel模板文件 * @return */ AjaxResult importHistoryDate(MultipartFile file, String historyDateType); } 3、ServiceImplpackage com.ctbr.base.service.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.ctbr.apply.service.IHistoryDataService; import com.ctbr.base.service.IHistoryDateMigrationDetailService; import com.ctbr.base.service.IHistoryDateMigrationService; import com.ctbr.baseFrame.core.AbstractBaseService; import com.ctbr.baseFrame.model.AjaxResult; import com.ctbr.baseFrame.util.StringUtil; import com.ctbr.baseFrame.util.UserContext; import com.ctbr.collateral.service.ICollateralRelieveApplyService; import com.ctbr.collateral.service.INeighbourhoodsManagerService; import com.ctbr.contract.service.IGCContractExcelService; import com.ctbr.financial.service.IFinancialFundPaymentService; import com.ctbr.financial.service.ISplitCustomerTempService; import com.ctbr.gc.service.ICustomerBaseService; import com.ctbr.gc.service.IRepayExtensionApplyService; import com.ctbr.gcapply.service.IApplyLoanCustomerRateService; import com.ctbr.gcapply.service.IRepayReleaseApplyService; import com.ctbr.gcapply.service.IRepayReleaseCustomerRateService; import com.ctbr.gcapply.service.IgcApplyLoanService; import com.ctbr.repay.service.IRepayExemptApplyService; import com.ctbr.repay.service.IRepayRefundApplyService; import com.ctbr.util.ExcelUtil; @Service("historyDateMigrationService") public class HistoryDateMigrationServiceImpl extends AbstractBaseService implements IHistoryDateMigrationService { @Resource(name="gcCustomerBaseService") private ICustomerBaseService customerBaseService; @Resource private IHistoryDataService historyDataService; @Override public String getTableMapping() { return "gc_history_date_migration_log"; } @Override public AjaxResult importHistoryDate(MultipartFile file, String historyDateType) { AjaxResult ajaxResult = new AjaxResult(); String pId = UUID.randomUUID().toString(); //记录日志表 Map<String,Object> migrationLogMap = new HashMap<String,Object>(); migrationLogMap.put("id", pId); migrationLogMap.put("file_name", file.getOriginalFilename()); migrationLogMap.put("business_type", historyDateType); migrationLogMap.put("oper_user_id", UserContext.getCurrentUser().getRealName()); migrationLogMap.put("oper_time", new Date()); try { ExcelUtil excelUtil = new ExcelUtil(); if("customer".equals(historyDateType)) {//客户 //调用工具类读取指定页数数据，0默认读取第一页 List<List<String>> excelDataList = excelUtil.readExcel(file, 0); System.out.println(excelDataList); List<String> errorMsg = customerBaseService.uploadHistoryData(excelDataList); if(errorMsg.size() > 0) { return ajaxResult.fail("505", errorMsg.get(0)); } }else if("collateral".equals(historyDateType)) {//抵押物 List<List<String>> list = excelUtil.readExcel(file, 0); //调用增加的方法 historyDataService.saveCollateral(list); } } catch (Exception e) { e.printStackTrace(); ajaxResult.fail("505", "系统异常！"); migrationLogMap.put("status", "失败"); this.baseDao.insert("gc_history_date_migration_log.insert",migrationLogMap); return ajaxResult; } migrationLogMap.put("status", "成功"); this.baseDao.insert("gc_history_date_migration_log.insert",migrationLogMap); return ajaxResult.success200(); } } 4、对应的导入增加的方法@Transactional @Override public AjaxResult saveCollateral(List<List<String>> data) { AjaxResult ajaxResult = new AjaxResult(); for(int i=1; i<data.size(); i++) { Map<String, Object> map = new HashMap<>(); List<String> row = data.get(i); //抵押物编号 map.put("collateral_no", row.get(0)); //押品类型 String collateral_type = row.get(1); if("房产".equals(StringUtils.trim(collateral_type))) { map.put("collateral_type", "2"); } else if("股权".equals(StringUtils.trim(collateral_type))) { map.put("collateral_type", "5"); } else { map.put("collateral_type", "6"); } //押品名称 String collateral_name = row.get(2); map.put("collateral_name", collateral_name); //权属人 String customer_name = row.get(3); //证件号码 String customer_card_no = row.get(4); Map<String, Object> customer = customerBaseService.getCustomerByCardNo(customer_card_no); if(customer == null) { throw new RuntimeException("客户 "+customer_name+"【"+customer_card_no+"】不存在"); } map.put("customer_id", customer.get("id")); map.put("collateral_use_status", "0"); map.put("delete_status", "0"); String collateral_id = warrantInfoService.addByUuid(map); if("房产".equals(StringUtils.trim(collateral_type))) { //共有人姓名 String co_owner_name = row.get(5); String[] names = co_owner_name.split(","); //共有人证件号 String co_owner_card_no = row.get(6); String[] card_nos = co_owner_card_no.split(","); //共有人权属证号 String co_certificate = row.get(7); String[] co_certificates = co_certificate.split(","); if(!(names.length==card_nos.length && card_nos.length==co_certificates.length)) { return ajaxResult.fail("500", "共有人姓名、证件号码、权属证信息必须个数相对应！"); } for(int j=0; j<names.length; j++) { Map<String, Object> co_owner_map = new HashMap<>(); Map<String, Object> co_owner = customerBaseService.getCustomerByCardNo(card_nos[j]); co_owner_map.put("customer_id", co_owner.get("id")); co_owner_map.put("collateral_id", collateral_id); String ownership_certificate = co_certificates[j]; if("无".equals(ownership_certificate)) { co_owner_map.put("have_ownership_certificate", "1"); } else { co_owner_map.put("have_ownership_certificate", "2"); co_owner_map.put("ownership_certificate",ownership_certificate); } coOwnerService.addByUuid(co_owner_map); } } } return ajaxResult.success200(); }5、ExcelUtilpackage com.ctbr.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; public class ExcelUtil { private String errorInfo; private static int readSheet = 0;//默认是0，读取第一个sheet页 private static boolean readSheetNum = true;//true开启自定义读取sheet页，false读取全部sheet页 public static void main(String[] args) throws Exception {} /** * 读取excel文件内容 * @param filePath 文件路径 * @param num 默认为0(读取第一页)，值为1时读取第二页 * @return 内容集合 */ public List<List<String>> readExcel(MultipartFile file, int num) { this.readSheet = num; List<List<String>> list = readExcel(file); return list; } /** * 读取excel文件内容 * @param filePath 文件路径 * @return 内容集合 */ public List<List<String>> readExcel(MultipartFile multfile) { List<List<String>> dataList = new ArrayList<List<String>>(); InputStream is = null; try { String fileName = multfile.getOriginalFilename(); if(fileName.endsWith("xls")){ is = multfile.getInputStream(); //2003 dataList = readFile(is, true); }else if(fileName.endsWith("xlsx")){ is = multfile.getInputStream(); //2007 dataList = readFile(is, false); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { is = null; e.printStackTrace(); } } } // 返回最后读取的结果 return dataList; } // 根据流读取Excel文件 public List<List<String>> readFile(InputStream inputStream, boolean is2003Excel) { List<List<String>> dataLists = null; try { // 根据版本选择创建Workbook的方式 Workbook wb = null; if (is2003Excel) { wb = new HSSFWorkbook(inputStream); } else { wb = new XSSFWorkbook(inputStream); } // sheet循环 int sheetNum = sheetCirculation(wb); List<List<String>> dataList = new ArrayList<List<String>>(); if (readSheetNum) { dataLists = read(dataList, wb, readSheet); } else { for (int i = 0; i < sheetNum; i++) { // Sheet sheet = wb.getSheetAt(i); // 显示sheet名称 // System.out.println(sheet.getSheetName()); dataLists = read(dataList, wb, i); } } } catch (IOException e) { e.printStackTrace(); } return dataLists; } // 读取数据 private List<List<String>> read(List<List<String>> dataList, Workbook wb, int sheets) { DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); // 总行数 int totalRows = 0; // 总列数 int totalCells = 0; // 第一个shell页 Sheet sheet = wb.getSheetAt(sheets); // Excel的行数 totalRows = sheet.getPhysicalNumberOfRows(); // Excel的列数 if (totalRows >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } DecimalFormat df = new DecimalFormat("#.######"); // 遍历Excel的行 for (int r = 0; r < totalRows; r++) { Row row = sheet.getRow(r); if (row == null) { continue; } List<String> rowLst = new ArrayList<String>(); // 遍历Excel的列 for (int c = 0; c < totalCells; c++) { Cell cell = row.getCell(c); String cellValue = ""; if (null != cell) { // 以下是判断数据的类型 switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: // 数字 if(DateUtil.isCellDateFormatted(cell)){//用于转化为日期格式 Date d = cell.getDateCellValue(); cellValue = formater.format(d); }else{ cellValue = df.format(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_STRING: // 字符串 cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean cellValue = cell.getBooleanCellValue() + ""; break; case HSSFCell.CELL_TYPE_FORMULA: // 公式 cellValue = cell.getCellFormula() + ""; break; case HSSFCell.CELL_TYPE_BLANK: // 空值 cellValue = ""; break; case HSSFCell.CELL_TYPE_ERROR: // 故障 cellValue = "非法字符"; break; default: cellValue = "未知类型"; break; } } rowLst.add(cellValue); } // 保存第r行的第c列 dataList.add(rowLst); } return dataList; } // 验证excel文件 public boolean validateExcel(String filePath) { // 检查文件名是否为空或者是否是Excel格式的文件 if (filePath == null || !(is2003Excel(filePath) || is2007Excel(filePath))) { errorInfo = "文件名不是excel格式"; return false; } // 检查文件是否存在 File file = new File(filePath); if (file == null || !file.exists()) { errorInfo = "excel文件不存在"; return false; } return true; } private int sheetCirculation(Workbook wb) { int sheetCount = -1; sheetCount = wb.getNumberOfSheets(); return sheetCount; } //是否是2003的excel，返回true是2003 public static boolean is2003Excel(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } //是否是2007的excel，返回true是2007 public static boolean is2007Excel(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } //得到错误信息 public String getErrorInfo() { return errorInfo; } /** * 文件类型转换，判断excel是2003还是2007 * @param cmfFile * @return */ public Map<String,Object> getFile(CommonsMultipartFile cmfFile) { CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)cmfFile; DiskFileItem diskFileItem = (DiskFileItem)commonsMultipartFile.getFileItem(); String name = diskFileItem.getName();//文件名 System.out.println("Excel文件名："+name); // 判断文件的类型，是2003还是2007 boolean is2003Excel = true; if (is2007Excel(name)) { is2003Excel = false; } File file = diskFileItem.getStoreLocation(); Map<String,Object> map = new HashMap<String, Object>(); map.put("is2003Excel", is2003Excel); map.put("file", file); return map; } }
java中的接口是类的蓝图。 它有静态常量和抽象方法。java中的接口是一种实现抽象的机制。 接口中只有抽象方法而不是方法体。接口用于在Java中实现抽象和多重继承。Java接口也表示IS-A关系。它不能像抽象类一样被实例化。为什么要使用Java接口？需要使用接口主要有三个原因。它用于实现抽象。通过接口，可以支持多重继承的功能。它可用于实现松耦合。Java 8，接口可以有默认和静态方法.换句话说，接口字段默认是public，static和final，方法默认是public和abstract。Java 8接口中的默认方法:从Java 8开始，我们可以在接口中有方法体。 但需要使其为默认方法。interface Drawable { void draw(); default void msg() { System.out.println("default method"); } } class Rectangle implements Drawable { public void draw() { System.out.println("drawing rectangle"); } } class TestInterfaceDefault { public static void main(String args[]) { Drawable d = new Rectangle(); d.draw(); d.msg(); } }执行上面代码，得到如下结果 -drawing rectangle default methodJava 8接口中的静态方法:从Java 8开始，我们可以在接口中有静态方法。interface Drawable { void draw(); static int cube(int x) { return x * x * x; } } class Rectangle implements Drawable { public void draw() { System.out.println("drawing rectangle"); } } class TestInterfaceStatic { public static void main(String args[]) { Drawable d = new Rectangle(); d.draw(); System.out.println(Drawable.cube(3)); } }执行上面代码，得到如下结果 -drawing rectangle 27Java嵌套接口注意： 一个接口中可以有另一个接口，即被称为嵌套接口。
在java中用abstract关键字声明的类称为抽象类。 它可以有抽象和非抽象方法(带主体的方法)。规则：如果在类中有任何抽象方法，那个类必须声明为抽象的。规则：如果你扩展任何具有抽象方法的抽象类，必须提供方法的实现或使这个类抽象化。Java中的抽象抽象是隐藏实现细节并仅向用户显示功能的过程。另一种方式，它只向用户显示重要的事情，并隐藏内部详细信息，例如：发送短信，只需输入文本并发送消息。您也不需要知道有关邮件传递的内部处理过程。抽象可以让你专注于对象做什么(实现的功能)，而不是它如何做。实现抽象的方法在java中有两种实现抽象的方法，它们分别是：抽象类(部分)接口 (完全)Java中的抽象类抽象类使用 abstract关键字声明的类被称为抽象类。需要扩展和实现它的方法。 它不能被实例化。abstract class A{};抽象方法一个被声明为 abstract 而没有实现的方法称为抽象方法。abstract void printStatus();抽象类的另一个真实场景抽象类也可以用于提供接口的一些实现。 在这种情况下，终端用户可能不会被强制覆盖接口的所有方法。
InnoDB和MyISAM的区别 MyISAMInnoDB事务支持不支持支持数据行锁不支持（表锁）支持外键约束不支持支持全文索引支持不支持表空间的大小较小较大，约为2倍常规使用操作：MyISAM 节约空间，数度较快InnoDB 安全性高，事务的支持，多表多用户操作在物理空间存在的位置所有的数据库文件都存在data目录下，一个文件夹就对应一个数据库本质还是文件的存储！MySQL引擎在物理文件上的区别InnoDB 在数据库表中只有*.frm文件，以及上级目录下的bdatal文件MyISAM 对应文件*.frm 表结构的定义文件*.MYD 数据文件（data）*.MYI 索引文件（index）设置数据库表的字符集编码CHARSET=utf-8不设置的话，会是MySQL默认的字符集编码（不支持中文）MySQL的默认编码是Latin1，不支持中文在my.ini中配置默认编码character-set-server=utf-8
1、进入设置2、选择Plugins -> 点击齿轮，选择第一个3、点击+，填入https://plugins.zhile.io4、搜索并安装ide eval reset，installed后点击ok5、关闭setting界面，点击help，选择Eval Reset（如果没有，请重新进行上一步）6、点击复选框，设置为自动重置7、点击Reset -> 弹窗选择yes，重启IDE8、总结Settings/Preferences... -> Plugins 内手动添加第三方插件仓库地址：https://plugins.zhile.io -> 安装ide eval reset并使用
1、jsp和对应的js文件1.1js//页面初始化就加载 $(function() { //表格列 /** *dataTables开始** */ dataTables = $('#articleListTable').DataTable({ "language": { "info": "当前 _START_ - _END_ 条 共 _TOTAL_ 条", "paginate": { "sFirst": "首页", "sPrevious": " < ", "sNext": " >", "sLast": " 尾页 " }, "emptyTable": "没有符合条件的记录!", "lengthMenu": "显示 _MENU_ 条", "sZeroRecords": "没有找到匹配的记录", "sInfoEmpty": "" }, "aLengthMenu": [10, 20, 50, 100], "pagingType": "full_numbers", // 用于指定分页器风格 // "full_numbers"" or // ""two_button""， // default // ""two_button"" "bAutoWidth": true, "scrollX": true, "ajax": { "url": path + "/appletManage/mpArticle/queryPage", "type": "POST", "dataType": "json", "data": { filter : filter } }, "processing": true, "serverSide": true, "bLengthChange": true, "bSort": false, // 排序功能 "searching": false, "bStateSave": false, // 保留分页信息 "resetPaging": false, "dom": '<"top">t<"bottom"lip><"clear">', "columns": [ //数据对应的内容 {"data": "ord"}, {"data": "status_flag_nm"}, {"data": "thumbnail_url"}, {"data": "title"}, //操作按钮，样式靠右 {"data": "","class": "align-right"} ], "columnDefs": [ { "render": function(data, type, row, meta) { //序号列 return meta.row + 1 + meta.settings._iDisplayStart; }, "orderable": false, //表示第一列 "targets": 0 }, { //如果表格中要显示图片，可以修改样式 "render": function(data, type, row) { var html = " "; //缩略图 return html; }, "orderable": false, "targets": 2 }, { "render":function(data,type,full){ return " "+data+" "; }, "targets": 3 },{ "render": function(data, type, row, meta) { var html = "";//编辑按钮 html += ' '; html += ' '; if(row.status_flag == "Y"){ html += ' '; }else{ html += ' '; } html += ' '; html += ' '; html += ' '; return html; }, "orderable": false, "targets": 4 }] }); });1.2jsp 序号 显示状态 缩略图 标题 操作 2、上移下移操作2.1、js文件/** * 上移下移 * */ function updateOrd(id,type,ord,rowIndex){ if(dataTables.rows()&& dataTables.rows().data()){ var data = dataTables.rows().data(); var nextIndex = 0; if(type == "up" && rowIndex == 0 ){ $.zkbr.alert("错误信息", "已经是第一条数据"); return false; } if(type == "down" && rowIndex == (data.length - 1)){ $.zkbr.alert("错误信息", "已经最后一条数据"); return false; } if(type == "up"){ nextIndex = rowIndex - 1; } else { nextIndex = rowIndex + 1; } // console.log(data[nextIndex]) $.ajax({ url: path+"/appletManage/mpArticle/updateOrd", type:"post", dataType:"json", params: null, data : { "id": id, "ord": data[nextIndex].ord, "nextId": data[nextIndex].id, "nextOrd": ord }, success:function(data){ if (data.statusCode == '200') { // 返回后显示方案状态为已初审分配 dataTables.ajax.reloadData({filter : filter}); } else { $.zkbr.alert("错误信息", data.errorMsg); } } }) } }2.2、controller/** * 上移下移，交换排序 * * @param id 文章ID * @param ord 旧的排序 * @param newOrd 新的排序 * @return */ @ResponseBody @RequestMapping(value = "/updateOrd") public AjaxResult updateOrd(String id, Integer ord, String nextId,Integer nextOrd) { if (null == id || StringUtils.isEmpty(id)) { return new AjaxResult().fail("500", "当前行ID不能为空"); } if (null == ord) { return new AjaxResult().fail("500", "当前行序号不能为空"); } if (null == nextId) { return new AjaxResult().fail("500", "移动行的ID不能为空"); } if (null == nextOrd) { return new AjaxResult().fail("500", "移动行序号不能为空"); } Map<String, Object> articleInfo = service.getOne(new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("id", id); } }); if (null == articleInfo) { return new AjaxResult().fail("500", "数据不存在"); } UserInfo userInfo = UserContext.getCurrentUser(); //更新当前行 service.updateOrd(new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("id", id); put("ord", ord); put("update_user", userInfo.getUserId()); } }); //更新互换的行 service.updateOrd(new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("id", nextId); put("ord", nextOrd); put("update_user", userInfo.getUserId()); } }); return new AjaxResult().success200(); }2.3、service/** * 修改序号 * * @param map */ public void updateOrd(Map<String, Object> map);2.4、serviceImpl/** * 修改序号 * * @param map */ @Override public void updateOrd(Map<String, Object> map) { baseDao.update(getTableMapping() + ".updateOrd", map); }2.5、mapper.xml<update id="updateOrd" parameterMap="paraMap"> update mp_article set ord = #{ord}, update_user = #{update_user}, update_date = current_timestamp where id = #{id} </update>