苦尽甘来 一个月学通JavaWeb(四十六 WMS系统)

2023-12-25 16:10

本文主要是介绍苦尽甘来 一个月学通JavaWeb(四十六 WMS系统),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

夜光序言:

前尘如梦独醉里

世间总是多情痴

终年不遇便深埋

安得生死许相思

 

 

 

正文:

 

package com.ken.wms.common.util;import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.*;/*** @author Ken /  Yeguang / Genius Team*/
public class ExcelUtil {// 默认配置文件名private static final String DEFAULT_FILE_NAME = "ExcelUtilConfig.xml";private XMLConfiguration xmlConfig;// 实体类与Excel的映射关系private Map<String, MappingInfo> excelMappingInfo;public ExcelUtil() {init(DEFAULT_FILE_NAME);}public ExcelUtil(String fileLocation) {init(fileLocation);}/*** 对 ExcelUtil 进行初始化 将扫描配置文件,加载配置的参数** @throws ConfigurationException*/private void init(String fileLocation) {// 创建对象的 excelMappingInfo 映射excelMappingInfo = new HashMap<>();Configurations configs = new Configurations();try {xmlConfig = configs.xml(fileLocation);} catch (ConfigurationException e) {e.printStackTrace();}if (xmlConfig == null) {return;}/** 扫描 XMl 并配置参数*/// 扫描 entity 节点List<Object> entities = xmlConfig.getList("entity[@class]");if (entities == null) {return;}int entityNum = entities.size();for (int i = 0; i < entityNum; i++) {MappingInfo mappingInfo = new MappingInfo();// 获得全限定类名String className = xmlConfig.getString("entity(" + i + ")[@class]");mappingInfo.setClassName(className);// 扫描 property 节点List<HierarchicalConfiguration<ImmutableNode>> properties = xmlConfig.configurationsAt("entity(" + i + ").property");for (HierarchicalConfiguration<ImmutableNode> property : properties) {// 解析String field = property.getString("field");String value = property.getString("value");mappingInfo.addFieldsMap(field, value);mappingInfo.addValuesMap(value, field);}// 将 entity 添加到 excelMappingInfoexcelMappingInfo.put(className, mappingInfo);}}/*** 讀取 Excel 文件中的内容 Excel 文件中的每一行代表了一个对象实例,而行中各列的属性值对应为对象中的各个属性值* 读取时,需要指定读取目标对象的类型以获得相关的映射信息,并且要求该对象已在配置文件中注册** @param classType 目标对象的类型* @param file      数据来源的 Excel 文件* @return 包含若干个目标对象实例的 List*/public List<Object> excelReader(Class<? extends Object> classType, MultipartFile file) {if (file == null)return null;// 初始化存放读取结果的 ListList<Object> content = new ArrayList<>();// 获取类名和映射信息String className = classType.getName();MappingInfo mappingInfo = excelMappingInfo.get(className);if (mappingInfo == null)return null;// 读取 Excel 文件try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {Sheet dataSheet = workbook.getSheetAt(0);Row row;Cell cell;Iterator<Row> rowIterator = dataSheet.iterator();Iterator<Cell> cellIterator;// 读取第一行表头信息if (!rowIterator.hasNext())return null;List<String> methodList = new ArrayList<>();// setter 方法列表List<Class<?>> fieldTypeList = new ArrayList<>();// 目标对象属性类型列表row = rowIterator.next();cellIterator = row.iterator();String field;while (cellIterator.hasNext()) {cell = cellIterator.next();field = mappingInfo.valuesMap.get(cell.getStringCellValue());Class<?> fieldType = classType.getDeclaredField(field).getType();fieldTypeList.add(cell.getColumnIndex(), fieldType);methodList.add(cell.getColumnIndex(), getSetterMethodName(field));}// 逐行读取表格内容,创建对象赋值并导入while (rowIterator.hasNext()) {row = rowIterator.next();cellIterator = row.iterator();Object elem = classType.newInstance();// 读取单元格while (cellIterator.hasNext()) {cell = cellIterator.next();int columnIndex = cell.getColumnIndex();Class<?> fieldType = fieldTypeList.get(columnIndex);String methodName = methodList.get(columnIndex);// 获取单元格的值,并设置对象中对应的属性Object value = getCellValue(fieldType, cell);if (value == null) continue;setField(elem, methodName, value);}// 放入结果content.add(elem);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return content;}/*** 将 List 中的元素对象写入到 Excel 中,其中每一个对象的一行,每一列的内容为对象的属性** @param classType 目标对象的类型* @param elems     数据来源的 List* @return*/public File excelWriter(Class<? extends Object> classType, List<?> elems) {if (classType == null || elems == null)return null;// 获取类名和映射信息String className = classType.getName();MappingInfo mappingInfo = excelMappingInfo.get(className);if (mappingInfo == null)return null;File excel = null;try {// 创建临时文件excel = File.createTempFile("excel", ".xslx");// 获取该 class 中定义的 field, 并将对应的信息保存到 List 中List<String> fieldList = new ArrayList<>();List<String> methodList = new ArrayList<>();List<String> valuesList = new ArrayList<>();Set<String> fields = mappingInfo.fieldsMap.keySet();if (fields == null)return null;for (String field : fields) {fieldList.add(field);methodList.add(getGetterMethodName(field));valuesList.add(mappingInfo.fieldsMap.get(field));}// 创建 workBook 对象Workbook workbook = new XSSFWorkbook();// 创建 sheet 对象Sheet sheet = workbook.createSheet();int rowCount = 0;int cellCount;Row row;Cell cell;// 写入第一行表头row = sheet.createRow(rowCount++);cellCount = 0;for (String value : valuesList) {cell = row.createCell(cellCount);cell.setCellValue(value);cellCount++;}// 写入内容数据for (Object elem : elems) {row = sheet.createRow(rowCount++);cellCount = 0;for (String methodName : methodList) {Object value = getField(elem, methodName);cell = row.createCell(cellCount++);setCellValue(value, workbook, cell);}}// 将 workBook 写入到 tempFile 中FileOutputStream outputStream = new FileOutputStream(excel);workbook.write(outputStream);outputStream.flush();outputStream.close();workbook.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return excel;}/*** 该方法用于获取单元格 cell 中的值** @param fieldType 指定获取的值的类型* @param cell      单元格* @return 单元格中的值*/private Object getCellValue(Class<?> fieldType, Cell cell) {if (cell == null)return null;int cellType = cell.getCellType();Object value = null;if (cellType == Cell.CELL_TYPE_STRING) {if (fieldType.equals(String.class)) {value = cell.getStringCellValue();}} else if (cellType == Cell.CELL_TYPE_NUMERIC) {if (fieldType.equals(String.class)) {value = new DecimalFormat("0").format(cell.getNumericCellValue());} else if (fieldType.equals(Date.class)) {// && HSSFDateUtil.isCellDateFormatted(cell)value = new Date(cell.getDateCellValue().getTime());} else if (fieldType.equals(Long.class)) {Double v = cell.getNumericCellValue();value = v.longValue();} else if (fieldType.equals(Integer.class)) {Double v = cell.getNumericCellValue();value = v.intValue();} else {value = cell.getNumericCellValue();}} else if (cellType == Cell.CELL_TYPE_BOOLEAN) {if (fieldType.equals(Boolean.class)) {value = cell.getBooleanCellValue();}} else if (cellType == Cell.CELL_TYPE_FORMULA) {} else if (cellType == Cell.CELL_TYPE_ERROR) {} else if (cellType == Cell.CELL_TYPE_BLANK) {}return value;}/*** 设置 Excel 单元格的值** @param value 值* @param cell  单元格*/private void setCellValue(Object value, Workbook workbook, Cell cell) {if (cell == null || value == null)return;Class<?> valueClassType = value.getClass();if (valueClassType.equals(String.class)) {String v = (String) value;cell.setCellValue(v);} else if (valueClassType.equals(Integer.class)) {Integer v = (Integer) value;cell.setCellValue(v);} else if (valueClassType.equals(Long.class)) {Long v = (Long) value;cell.setCellValue(v);} else if (valueClassType.equals(Double.class)) {Double v = (Double) value;cell.setCellValue(v);} else if (valueClassType.equals(Boolean.class)) {Boolean v = (Boolean) value;cell.setCellValue(v);} else if (valueClassType.equals(Date.class)) {Date v = (Date) value;CellStyle cellStyle = workbook.createCellStyle();CreationHelper creationHelper = workbook.getCreationHelper();cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy/mm/dd"));cell.setCellValue(v);cell.setCellStyle(cellStyle);}}/*** 该方法用于设置对象中属性的值 通过调用目标对象属性对应的 setter 方法,因而要求目标对象必须设置 setter对象,否则赋值不成功** @param targetObject 目标对象* @param methodName   setter 方法名* @param field        方法参数的值* @throws Exception*/private void setField(Object targetObject, String methodName, Object field) throws Exception {// 获得 setter 方法实例Class<?> targetObjectType = targetObject.getClass();Class<?> fieldType = field.getClass();Method setterMethod = targetObjectType.getMethod(methodName, fieldType);// 调用方法setterMethod.invoke(targetObject, field);}/*** 获取目标对象中某个属性的值,通过调用目标对象属性对应的 getter 方法,因而要求目标对象必须设置 getter 对象,否则赋值不成功** @param targetObject 目标对象* @param methodName   getter 方法名* @return 返回该属性的值* @throws Exception*/private Object getField(Object targetObject, String methodName) throws Exception {// 获得 getter 方法实例Class<?> targetObjectType = targetObject.getClass();Method getterMethod = targetObjectType.getMethod(methodName);// 调用方法return getterMethod.invoke(targetObject);}/*** 构造 setter 方法的方法名** @param field 字段名* @return*/private String getSetterMethodName(String field) {// 转换为首字母大写String name = field.replaceFirst(field.substring(0, 1), field.substring(0, 1).toUpperCase());// 拼接 set 并返回return "set" + name;}/*** 构造 getter 方法的方法名** @param field 字段名* @return*/private String getGetterMethodName(String field) {// 转换为首字母大写String name = field.replaceFirst(field.substring(0, 1), field.substring(0, 1).toUpperCase());// 拼接 get 并返回return "get" + name;}/*** 该对象代表了各个注册到 ExcelUtil 对象的映射信息 映射信息包括:注册对象的类型,对象属性与 Excel 列名的映射** @author Ken*/private class MappingInfo {private String className;private Map<String, String> fieldsMap = new HashMap<>();private Map<String, String> valuesMap = new HashMap<>();@SuppressWarnings("unused")public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public void addFieldsMap(String field, String value) {fieldsMap.put(field, value);}public void addValuesMap(String value, String field) {valuesMap.put(value, field);}}
}
package com.ken.wms.common.util;import org.apache.commons.collections.map.HashedMap;import java.util.Map;/*** controller 返回的信息载体 response* @author ken /  Yeguang / Genius Team** Created by Genius Team*/
public class Response {public static final String RESPONSE_RESULT_SUCCESS = "success";public static final String RESPONSE_RESULT_ERROR = "error";// response 中可能使用的值private static final String RESPONSE_RESULT = "result";private static final String RESPONSE_MSG = "msg";private static final String RESPONSE_DATA = "data";private static final String RESPONSE_TOTAL = "total";// 存放响应中的信息private Map<String,Object> responseContent;// ConstructorResponse() {this.responseContent = new HashedMap(10);}/*** 设置 response 的状态* @param result response 的状态,值为 success 或 error*/public void setResponseResult(String result){this.responseContent.put(Response.RESPONSE_RESULT,result);}/*** 设置 response 的附加信息* @param msg response  的附加信息*/public void setResponseMsg(String msg){this.responseContent.put(Response.RESPONSE_MSG,msg);}/*** 设置 response 中携带的数据* @param data response 中携带的数据*/public void setResponseData(Object data){this.responseContent.put(Response.RESPONSE_DATA,data);}/*** 设置 response 中携带数据的数量,与 RESPONSE_DATA 配合使用* @param total 携带数据的数量*/public void setResponseTotal(long total){this.responseContent.put(Response.RESPONSE_TOTAL,total);}/*** 设置 response 自定义信息* @param key 自定义信息的 key* @param value 自定义信息的值*/public void setCustomerInfo(String key, Object value){this.responseContent.put(key,value);}/*** 生成 response* @return 代表 response 的一个 Map 对象*/public Map<String, Object> generateResponse(){return this.responseContent;}
}
package com.ken.wms.common.util;import org.springframework.stereotype.Component;/*** Response Utils* Created by Ken /  Yeguang / Genius Team*/
@Component
public class ResponseUtil {/*** 生成一个 Response 对象* @return response 对象*/public Response newResponseInstance(){Response response = new Response();return response;}}

 

 

 

 

 

这篇关于苦尽甘来 一个月学通JavaWeb(四十六 WMS系统)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/536104

相关文章

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.