1.引入jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>2.后端代码package com.atguigu.gulimall.product.web; import com.atguigu.gulimall.product.entity.CategoryEntity; import com.atguigu.gulimall.product.service.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; @Controller public class IndexController { @Autowired CategoryService categoryService; @GetMapping({"/", "/index.html"}) public String indexPage(Model model) { //1.查出所有的一级分类 List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys(); model.addAttribute("categorys", categoryEntities); //视图解析器进行拼串 //"classpath:/templates/" +返回值+ ".html" return "index"; } }3.在resource下新建templates文件夹（页面都放进这里面） 谷粒商城2020 X 家用电器 Hi, 欢迎来到! 登录 注册 新人福利 PLUS会员 促销 公告 更多 全民纸巾大作战 家具建材满999减300元 黑科技冰箱，下单立减千元 抢102减101神券！ 关于召回普利司通（天津）轮胎有限公司2个规格乘用车轮胎的公告 物流推出配送员统一外呼电话"95056” 天府大件运营中心开仓公告 大件物流“送装一体”服务全面升级！ 话费 机票 酒店 游戏 企业购 加油卡 电影票 火车票 众筹 理财 礼品卡 白条 话费 机票 酒店 游戏 X 话费充值 流量充值 套餐变更 号码 面值 100元 20元 50元 10元 2元 ￥98.0-￥100.0 快速充值 抢99减50元话费 X 国际机票 国际/港澳 特惠活动 单程 往返 机票查询 当季热门特惠机票 X 国内港澳台 促销活动 酒店查询 订酒店到 X 点卡 QQ 页游 面值 面值 面值 面值 ￥0.00 直充 卡密 快速充值 吃鸡就要快人一步 4.简单语法示例，更多语法参考官网https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html Welcome to our grocery store! 5.修改Thymeleaf的文件后能及时在页面更新，则要关闭缓存spring: thymeleaf: cache: false6.如果resource下的static文件读取不到时，可以加入以下配置或者在pom文件中加入spring: mvc: static-path-pattern: /static/**或者在pom文件中加入以下配置<resources> <resource> <filtering>false</filtering> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.yml</include> <include>static/**</include> </includes> </resource> </resources>
子页面 <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input> <el-tree :data="menus" :props="defaultProps" node-key="catId" ref="menuTree" @node-click="nodeclick" :filter-node-method="filterNode" :highlight-current="true"></el-tree> 父页面 <el-row :gutter="20"> <el-col :span="6"> <category @tree-node-click="treenodeclick"></category> </el-col> <el-col :span="18"> </el-col> </el-row> 总结：父子组件传递数据子组件给父组件传递数据，事件机制；子组件给父组件发送一个事件，携带上数据。this.$emit("事件名",携带的数据...)
//获取传过来的值 function getParams(key) { var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; }; var a_id = getParams("a_id");
文件名不能包含的字符//params['name']是标签获取得到的值 var reg = new RegExp('[\\\\/:*?\"<>|]'); if (reg.test(params['name'])) { $.zkbr.alert("提示信息", '文件名不能包含下列任何字符?、╲、/、*、"、<、>、|'); return; }不给输入单引号字符var reg = new RegExp('^[^‘’'\s]+$'); if(reg.test(params['title'])){ $.zkbr.alert("提示信息", "文章标题不能输入单引号"); return; }
定义一个数组var fruits = ["Banana", "Orange", "Apple", "Mango"];使用join（）方法var energy = fruits.join();输出energy//Banana,Orange,Apple,Mango console.log(energy);总结JavaScript Array join() 方法可以使数组拼接成字符串，并自动用‘’ , ‘’拼接
我们在开发前端项目时，一般会对用户敏感信息（如姓名、手机号码、身份证号码）进行脱敏处理。本文以手机号码脱敏处理为例进行说明。如 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(); });
修改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; } }
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>