苦尽甘来 一个月学通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将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依