瀏覽代碼

初始化

wanxl 2 年之前
父節點
當前提交
aa16ebbca8
共有 100 個文件被更改,包括 10350 次插入10350 次删除
  1. 38 38
      .gitignore
  2. 1 1
      README.md
  3. 247 247
      pom.xml
  4. 84 84
      src/main/java/com/template/AutoCode.java
  5. 19 19
      src/main/java/com/template/MybatisPlusApplication.java
  6. 12 12
      src/main/java/com/template/annotation/ControllerIsShow.java
  7. 17 17
      src/main/java/com/template/annotation/DESRespondSecret.java
  8. 18 18
      src/main/java/com/template/annotation/ExcelExport.java
  9. 19 19
      src/main/java/com/template/annotation/ExcelImport.java
  10. 28 28
      src/main/java/com/template/annotation/PassToken.java
  11. 14 14
      src/main/java/com/template/annotation/UserLoginCheck.java
  12. 95 95
      src/main/java/com/template/aop/DESResponseSecretAspect.java
  13. 45 45
      src/main/java/com/template/aop/LoginCheckAspect.java
  14. 49 49
      src/main/java/com/template/api/BookingControllerAPI.java
  15. 27 27
      src/main/java/com/template/api/CateringControllerAPI.java
  16. 18 18
      src/main/java/com/template/api/ExcelControllerAPI.java
  17. 36 36
      src/main/java/com/template/api/HotelControllerAPI.java
  18. 21 21
      src/main/java/com/template/api/LogInfoControllerAPI.java
  19. 34 34
      src/main/java/com/template/api/LoginControllerAPI.java
  20. 45 45
      src/main/java/com/template/api/ParkingControllerAPI.java
  21. 35 35
      src/main/java/com/template/api/RepairAdminControllerAPI.java
  22. 16 16
      src/main/java/com/template/api/SmsCodeControllerAPI.java
  23. 31 31
      src/main/java/com/template/api/SpecialityControllerAPI.java
  24. 50 50
      src/main/java/com/template/api/SystemMenuControllerAPI.java
  25. 37 37
      src/main/java/com/template/api/ToiletBaseControllerAPI.java
  26. 28 28
      src/main/java/com/template/api/WarmSmokeControllerAPI.java
  27. 16 16
      src/main/java/com/template/common/constanst/Constanst.java
  28. 14 14
      src/main/java/com/template/common/exception/EmsException.java
  29. 199 199
      src/main/java/com/template/common/exception/EmsExceptionHandler.java
  30. 29 29
      src/main/java/com/template/common/exception/MyCustomException.java
  31. 43 43
      src/main/java/com/template/common/jh/ReqRespResearchProductQuestionnaireItem.java
  32. 243 243
      src/main/java/com/template/common/jh/SectionUtil.java
  33. 7 7
      src/main/java/com/template/common/result/Code.java
  34. 83 83
      src/main/java/com/template/common/result/ResponseStatusEnum.java
  35. 23 23
      src/main/java/com/template/common/utils/AccessToken.java
  36. 84 84
      src/main/java/com/template/common/utils/AesTestOne.java
  37. 165 165
      src/main/java/com/template/common/utils/AesUtil.java
  38. 199 199
      src/main/java/com/template/common/utils/AesUtils.java
  39. 47 47
      src/main/java/com/template/common/utils/Base64Util.java
  40. 211 211
      src/main/java/com/template/common/utils/CommonUtil.java
  41. 9 9
      src/main/java/com/template/common/utils/DataBliu.java
  42. 241 241
      src/main/java/com/template/common/utils/DateUtils.java
  43. 82 82
      src/main/java/com/template/common/utils/EncryptUtil.java
  44. 41 41
      src/main/java/com/template/common/utils/EncryptionUtil.java
  45. 74 74
      src/main/java/com/template/common/utils/ExcelClassField.java
  46. 22 22
      src/main/java/com/template/common/utils/ExcelUtil3.java
  47. 64 64
      src/main/java/com/template/common/utils/ExcelUtils.java
  48. 1007 1007
      src/main/java/com/template/common/utils/ExcelUtils2.java
  49. 76 76
      src/main/java/com/template/common/utils/FileUtils.java
  50. 18 18
      src/main/java/com/template/common/utils/GetVertifyCode.java
  51. 241 241
      src/main/java/com/template/common/utils/HttpClientUtils.java
  52. 112 112
      src/main/java/com/template/common/utils/HttpUtils.java
  53. 530 530
      src/main/java/com/template/common/utils/HttpsClient.java
  54. 105 105
      src/main/java/com/template/common/utils/JWTUtil.java
  55. 54 54
      src/main/java/com/template/common/utils/Md5Utils.java
  56. 548 548
      src/main/java/com/template/common/utils/Message.java
  57. 113 113
      src/main/java/com/template/common/utils/Message2.java
  58. 23 23
      src/main/java/com/template/common/utils/MyX509TrustManager.java
  59. 99 99
      src/main/java/com/template/common/utils/PropertiesUtil.java
  60. 196 196
      src/main/java/com/template/common/utils/RSAUtils.java
  61. 32 32
      src/main/java/com/template/common/utils/RandomTrackAlgorithm.java
  62. 126 126
      src/main/java/com/template/common/utils/RequestUtils.java
  63. 42 42
      src/main/java/com/template/common/utils/SHA1.java
  64. 213 213
      src/main/java/com/template/common/utils/SendSms.java
  65. 748 748
      src/main/java/com/template/common/utils/TimeExchange.java
  66. 628 628
      src/main/java/com/template/common/utils/TimeExchange2.java
  67. 25 25
      src/main/java/com/template/common/utils/UUIDUtil.java
  68. 25 25
      src/main/java/com/template/common/utils/ValidateCode.java
  69. 52 52
      src/main/java/com/template/common/utils/WxConfig.java
  70. 53 53
      src/main/java/com/template/common/utils/WxConstants.java
  71. 385 385
      src/main/java/com/template/common/utils/WxUtil.java
  72. 47 47
      src/main/java/com/template/common/utils/imageUtils.java
  73. 27 27
      src/main/java/com/template/common/utils/paramUtils.java
  74. 25 25
      src/main/java/com/template/common/utils/smsUtil.java
  75. 53 53
      src/main/java/com/template/config/CosConfig.java
  76. 52 52
      src/main/java/com/template/config/MyBatisPlusConfig.java
  77. 37 37
      src/main/java/com/template/config/MySecurity.java
  78. 36 36
      src/main/java/com/template/config/smsConfig.java
  79. 111 111
      src/main/java/com/template/controller/BookingController.java
  80. 46 46
      src/main/java/com/template/controller/CateringController.java
  81. 89 89
      src/main/java/com/template/controller/ExcelController.java
  82. 76 76
      src/main/java/com/template/controller/HotelController.java
  83. 32 32
      src/main/java/com/template/controller/LogInfoController.java
  84. 161 161
      src/main/java/com/template/controller/LoginController.java
  85. 120 120
      src/main/java/com/template/controller/ParkingController.java
  86. 163 163
      src/main/java/com/template/controller/RepairAdminController.java
  87. 42 42
      src/main/java/com/template/controller/SmsCodeController.java
  88. 57 57
      src/main/java/com/template/controller/SpecialityController.java
  89. 110 110
      src/main/java/com/template/controller/SystemMenuController.java
  90. 122 122
      src/main/java/com/template/controller/ToiletBaseController.java
  91. 60 60
      src/main/java/com/template/controller/WarmSmokeController.java
  92. 27 27
      src/main/java/com/template/core/CORSConfiguration.java
  93. 113 113
      src/main/java/com/template/core/JwtAuthenticationInterceptor.java
  94. 25 25
      src/main/java/com/template/core/JwtlnterceptorConfig.java
  95. 74 74
      src/main/java/com/template/core/SwaggerConfiguration.java
  96. 26 26
      src/main/java/com/template/handle/NonStaticResourceHttpRequestHandler.java
  97. 60 60
      src/main/java/com/template/handler/MyMetaObjectHandler.java
  98. 93 93
      src/main/java/com/template/mapper/BookingMapper.java
  99. 55 55
      src/main/java/com/template/mapper/HotelMapper.java
  100. 0 0
      src/main/java/com/template/mapper/ParkingMapper.java

+ 38 - 38
.gitignore

@@ -1,38 +1,38 @@
-# Java
-*.class
-*.jar
-*.war
-*.ear
-
-# Eclipse
-.project
-.classpath
-.settings
-
-# Idea
-.idea
-*.iml
-*.iws
-*.ipr
-
-# OS
-Thumbs.db
-.DS_Store
-
-# Gradle
-.gradle
-!gradle-wrapper.jar
-
-# Maven
-target
-
-# Build
-out
-build
-bin
-
-# Other
-*.log
-*.swp
-*.bak
-
+# Java
+*.class
+*.jar
+*.war
+*.ear
+
+# Eclipse
+.project
+.classpath
+.settings
+
+# Idea
+.idea
+*.iml
+*.iws
+*.ipr
+
+# OS
+Thumbs.db
+.DS_Store
+
+# Gradle
+.gradle
+!gradle-wrapper.jar
+
+# Maven
+target
+
+# Build
+out
+build
+bin
+
+# Other
+*.log
+*.swp
+*.bak
+

+ 1 - 1
README.md

@@ -1 +1 @@
-#Back-endDevelopmentFramework
+#Back-endDevelopmentFramework

+ 247 - 247
pom.xml

@@ -1,247 +1,247 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
-    <modelVersion>4.0.0</modelVersion>
-    <parent>
-        <groupId>org.springframework.boot</groupId>
-        <artifactId>spring-boot-starter-parent</artifactId>
-        <version>2.4.0</version>
-        <relativePath/> <!-- lookup parent from repository -->
-    </parent>
-    <groupId>com.template</groupId>
-    <artifactId>jayq_java_newtravel</artifactId>
-    <version>0.0.1-SNAPSHOT</version>
-    <name>jayq_java_newtravel</name>
-    <description>Demo project for Spring Boot</description>
-
-    <properties>
-        <java.version>1.8</java.version>
-        <tencent.qcloudsms.version>1.0.6</tencent.qcloudsms.version>
-    </properties>
-
-    <dependencies>
-
-        <dependency>
-            <groupId>javax.validation</groupId>
-            <artifactId>validation-api</artifactId>
-            <version>2.0.1.Final</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.hibernate</groupId>
-            <artifactId>hibernate-validator</artifactId>
-            <version>6.1.5.Final</version>
-        </dependency>
-
-        <!--   读取excel数据     -->
-        <dependency>
-            <groupId>org.apache.poi</groupId>
-            <artifactId>poi</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.poi</groupId>
-            <artifactId>poi-ooxml</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-
-        <!-- fastjson -->
-        <dependency>
-            <groupId>com.alibaba</groupId>
-            <artifactId>fastjson</artifactId>
-            <version>2.0.12</version>
-        </dependency>
-
-        <!--引入JWT-->
-        <dependency>
-            <groupId>com.auth0</groupId>
-            <artifactId>java-jwt</artifactId>
-            <version>3.10.0</version>
-        </dependency>
-        <dependency>
-            <groupId>io.jsonwebtoken</groupId>
-            <artifactId>jjwt</artifactId>
-            <version>0.9.1</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.github.qcloudsms</groupId>
-            <artifactId>qcloudsms</artifactId>
-            <version>${tencent.qcloudsms.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.tencentcloudapi</groupId>
-            <artifactId>tencentcloud-sdk-java</artifactId>
-            <version>3.1.742</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-aop</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.httpcomponents</groupId>
-            <artifactId>httpclient</artifactId>
-            <version>4.5.10</version>
-        </dependency>
-        <dependency>
-            <groupId>com.google.code.gson</groupId>
-            <artifactId>gson</artifactId>
-            <version>2.8.7</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-quartz</artifactId>
-        </dependency>
-        <!-- 数据库驱动 -->
-        <dependency>
-            <groupId>mysql</groupId>
-            <artifactId>mysql-connector-java</artifactId>
-        </dependency>
-        <!-- lombok -->
-        <dependency>
-            <groupId>org.projectlombok</groupId>
-            <artifactId>lombok</artifactId>
-        </dependency>
-        <!-- mybatis-plus -->
-        <!-- mybatis-plus 是自己开发,并非官方的! -->
-        <dependency>
-            <groupId>com.baomidou</groupId>
-            <artifactId>mybatis-plus-boot-starter</artifactId>
-            <version>3.0.5</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-web</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-test</artifactId>
-            <scope>test</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.junit.vintage</groupId>
-                    <artifactId>junit-vintage-engine</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-web</artifactId>
-            <version>5.3.22</version>
-        </dependency>
-
-        <!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
-        <dependency>
-            <groupId>org.eclipse.jgit</groupId>
-            <artifactId>org.eclipse.jgit</artifactId>
-            <version>5.4.3.201909031940-r</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-configuration-processor</artifactId>
-            <optional>true</optional>
-        </dependency>
-
-        <!-- redis -->
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-redis</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>io.lettuce</groupId>
-                    <artifactId>lettuce-core</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>redis.clients</groupId>
-            <artifactId>jedis</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>io.springfox</groupId>
-            <artifactId>springfox-swagger2</artifactId>
-            <version>2.9.2</version>
-        </dependency>
-        <dependency>
-            <groupId>io.springfox</groupId>
-            <artifactId>springfox-swagger-ui</artifactId>
-            <version>2.9.2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.velocity</groupId>
-            <artifactId>velocity-engine-core</artifactId>
-            <version>2.0</version>
-        </dependency>
-        <dependency>
-            <groupId>jakarta.validation</groupId>
-            <artifactId>jakarta.validation-api</artifactId>
-            <version>2.0.2</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.qcloud</groupId>
-            <artifactId>cos_api</artifactId>
-            <version>5.6.155</version>
-        </dependency>
-
-
-        <!--hutools-->
-        <dependency>
-            <groupId>cn.hutool</groupId>
-            <artifactId>hutool-all</artifactId>
-            <version>5.4.3</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.github.pagehelper</groupId>
-            <artifactId>pagehelper-spring-boot-starter</artifactId>
-            <version>1.4.2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-test</artifactId>
-            <version>6.0.9</version>
-            <scope>compile</scope>
-        </dependency>
-
-        <!-- 上传文件的依赖 -->
-        <dependency>
-            <!--common-fileupload的依赖组件-->
-            <groupId>commons-io</groupId>
-            <artifactId>commons-io</artifactId>
-            <version>2.6</version>
-        </dependency>
-        <dependency>
-            <groupId>commons-fileupload</groupId>
-            <artifactId>commons-fileupload</artifactId>
-            <version>1.4</version>
-        </dependency>
-        <dependency>
-            <groupId>com.alibaba</groupId>
-            <artifactId>druid</artifactId>
-            <version>1.2.16</version>
-        </dependency>
-        <dependency>
-            <groupId>com.alibaba</groupId>
-            <artifactId>easyexcel</artifactId>
-            <version>2.2.11</version>
-        </dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.springframework.boot</groupId>
-                <artifactId>spring-boot-maven-plugin</artifactId>
-            </plugin>
-        </plugins>
-    </build>
-
-</project>
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.4.0</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.template</groupId>
+    <artifactId>jayq_java_newtravel</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>jayq_java_newtravel</name>
+    <description>Demo project for Spring Boot</description>
+
+    <properties>
+        <java.version>1.8</java.version>
+        <tencent.qcloudsms.version>1.0.6</tencent.qcloudsms.version>
+    </properties>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <version>2.0.1.Final</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.hibernate</groupId>
+            <artifactId>hibernate-validator</artifactId>
+            <version>6.1.5.Final</version>
+        </dependency>
+
+        <!--   读取excel数据     -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+
+        <!-- fastjson -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>2.0.12</version>
+        </dependency>
+
+        <!--引入JWT-->
+        <dependency>
+            <groupId>com.auth0</groupId>
+            <artifactId>java-jwt</artifactId>
+            <version>3.10.0</version>
+        </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.1</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.qcloudsms</groupId>
+            <artifactId>qcloudsms</artifactId>
+            <version>${tencent.qcloudsms.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.tencentcloudapi</groupId>
+            <artifactId>tencentcloud-sdk-java</artifactId>
+            <version>3.1.742</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.10</version>
+        </dependency>
+        <dependency>
+            <groupId>com.google.code.gson</groupId>
+            <artifactId>gson</artifactId>
+            <version>2.8.7</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-quartz</artifactId>
+        </dependency>
+        <!-- 数据库驱动 -->
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+        </dependency>
+        <!-- lombok -->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
+        <!-- mybatis-plus -->
+        <!-- mybatis-plus 是自己开发,并非官方的! -->
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.0.5</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.junit.vintage</groupId>
+                    <artifactId>junit-vintage-engine</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-web</artifactId>
+            <version>5.3.22</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
+        <dependency>
+            <groupId>org.eclipse.jgit</groupId>
+            <artifactId>org.eclipse.jgit</artifactId>
+            <version>5.4.3.201909031940-r</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-configuration-processor</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <!-- redis -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+            <exclusions>
+                <exclusion>
+                    <groupId>io.lettuce</groupId>
+                    <artifactId>lettuce-core</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+        <dependency>
+            <groupId>redis.clients</groupId>
+            <artifactId>jedis</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+            <version>2.9.2</version>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+            <version>2.9.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.velocity</groupId>
+            <artifactId>velocity-engine-core</artifactId>
+            <version>2.0</version>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.validation</groupId>
+            <artifactId>jakarta.validation-api</artifactId>
+            <version>2.0.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.qcloud</groupId>
+            <artifactId>cos_api</artifactId>
+            <version>5.6.155</version>
+        </dependency>
+
+
+        <!--hutools-->
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>5.4.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.github.pagehelper</groupId>
+            <artifactId>pagehelper-spring-boot-starter</artifactId>
+            <version>1.4.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-test</artifactId>
+            <version>6.0.9</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <!-- 上传文件的依赖 -->
+        <dependency>
+            <!--common-fileupload的依赖组件-->
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.6</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>1.4</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid</artifactId>
+            <version>1.2.16</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel</artifactId>
+            <version>2.2.11</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 84 - 84
src/main/java/com/template/AutoCode.java

@@ -1,84 +1,84 @@
-package com.template;
-
-import com.baomidou.mybatisplus.annotation.DbType;
-import com.baomidou.mybatisplus.annotation.FieldFill;
-import com.baomidou.mybatisplus.annotation.IdType;
-import com.baomidou.mybatisplus.generator.AutoGenerator;
-import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
-import com.baomidou.mybatisplus.generator.config.GlobalConfig;
-import com.baomidou.mybatisplus.generator.config.PackageConfig;
-import com.baomidou.mybatisplus.generator.config.StrategyConfig;
-import com.baomidou.mybatisplus.generator.config.po.TableFill;
-import com.baomidou.mybatisplus.generator.config.rules.DateType;
-import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
-
-import java.util.ArrayList;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 15:46
- * @Description: com.video
- * @Version: 1.0
- */
-public class AutoCode {
-    public static void main(String[] args) {
-// 需要构建一个 代码自动生成器 对象
-        AutoGenerator mpg = new AutoGenerator();
-// 配置策略
-// 1、全局配置
-        GlobalConfig gc = new GlobalConfig();
-        String projectPath = System.getProperty("user.dir");
-        gc.setOutputDir(projectPath + "/src/main/java");
-        gc.setAuthor("ceshi");
-        gc.setOpen(false);
-        gc.setFileOverride(false); // 是否覆盖
-        gc.setServiceName("%sService"); // 去Service的I前缀
-        gc.setIdType(IdType.UUID);
-        gc.setDateType(DateType.ONLY_DATE);
-        gc.setSwagger2(true);
-        mpg.setGlobalConfig(gc);
-//2、设置数据源
-        DataSourceConfig dsc = new DataSourceConfig();
-        dsc.setUrl("jdbc:mysql://192.168.161.220:3306/repair_report?useUnicode=tru&characterEncoding=UTF-8&useSSL=false&useAffectedRows=true&allowPublicKeyRetrieval=true&allowMultiQueries=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai");
-        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
-        dsc.setUsername("root");
-        dsc.setPassword("root");
-        dsc.setDbType(DbType.MYSQL);
-        mpg.setDataSource(dsc);
-        //3、包的配置
-        PackageConfig pc = new PackageConfig();
-        pc.setModuleName("auto");
-        pc.setParent("com.template");
-        pc.setEntity("model");
-        pc.setMapper("mapper");
-        pc.setService("services");
-        pc.setController("controller");
-        mpg.setPackageInfo(pc);
-        //4、策略配置
-        StrategyConfig strategy = new StrategyConfig();
-        strategy.setInclude("repair_admin"); // 设置要映射的表名
-        strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰
-        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//下划线转驼峰
-        strategy.setEntityLombokModel(true); // 自动lombok;
-        strategy.setLogicDeleteFieldName("deleted");//逻辑删除 调用service的删除方法不会真删除 会把deleted字段的值改为1 (未删除="0",删除="1")
-        // 自动填充配置
-        TableFill deletedCreate = new TableFill("deleted", FieldFill.INSERT);
-        TableFill timeCreate = new TableFill("create_time", FieldFill.INSERT);
-        TableFill userCreate = new TableFill("create_user", FieldFill.INSERT);
-        TableFill timeModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
-        TableFill userModified = new TableFill("update_user", FieldFill.INSERT_UPDATE);
-        ArrayList<TableFill> tableFills = new ArrayList<>();
-        tableFills.add(deletedCreate);
-        tableFills.add(timeCreate);
-        tableFills.add(userCreate);
-        tableFills.add(timeModified);
-        tableFills.add(userModified);
-        strategy.setTableFillList(tableFills);
-        // 乐观锁
-        strategy.setVersionFieldName("version");
-        strategy.setRestControllerStyle(true);
-        strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
-        mpg.setStrategy(strategy);
-        mpg.execute(); //执行
-    }
-}
+package com.template;
+
+import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.annotation.FieldFill;
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.generator.AutoGenerator;
+import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.PackageConfig;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.po.TableFill;
+import com.baomidou.mybatisplus.generator.config.rules.DateType;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+
+import java.util.ArrayList;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 15:46
+ * @Description: com.video
+ * @Version: 1.0
+ */
+public class AutoCode {
+    public static void main(String[] args) {
+// 需要构建一个 代码自动生成器 对象
+        AutoGenerator mpg = new AutoGenerator();
+// 配置策略
+// 1、全局配置
+        GlobalConfig gc = new GlobalConfig();
+        String projectPath = System.getProperty("user.dir");
+        gc.setOutputDir(projectPath + "/src/main/java");
+        gc.setAuthor("ceshi");
+        gc.setOpen(false);
+        gc.setFileOverride(false); // 是否覆盖
+        gc.setServiceName("%sService"); // 去Service的I前缀
+        gc.setIdType(IdType.UUID);
+        gc.setDateType(DateType.ONLY_DATE);
+        gc.setSwagger2(true);
+        mpg.setGlobalConfig(gc);
+//2、设置数据源
+        DataSourceConfig dsc = new DataSourceConfig();
+        dsc.setUrl("jdbc:mysql://192.168.161.220:3306/repair_report?useUnicode=tru&characterEncoding=UTF-8&useSSL=false&useAffectedRows=true&allowPublicKeyRetrieval=true&allowMultiQueries=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai");
+        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
+        dsc.setUsername("root");
+        dsc.setPassword("root");
+        dsc.setDbType(DbType.MYSQL);
+        mpg.setDataSource(dsc);
+        //3、包的配置
+        PackageConfig pc = new PackageConfig();
+        pc.setModuleName("auto");
+        pc.setParent("com.template");
+        pc.setEntity("model");
+        pc.setMapper("mapper");
+        pc.setService("services");
+        pc.setController("controller");
+        mpg.setPackageInfo(pc);
+        //4、策略配置
+        StrategyConfig strategy = new StrategyConfig();
+        strategy.setInclude("repair_admin"); // 设置要映射的表名
+        strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰
+        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//下划线转驼峰
+        strategy.setEntityLombokModel(true); // 自动lombok;
+        strategy.setLogicDeleteFieldName("deleted");//逻辑删除 调用service的删除方法不会真删除 会把deleted字段的值改为1 (未删除="0",删除="1")
+        // 自动填充配置
+        TableFill deletedCreate = new TableFill("deleted", FieldFill.INSERT);
+        TableFill timeCreate = new TableFill("create_time", FieldFill.INSERT);
+        TableFill userCreate = new TableFill("create_user", FieldFill.INSERT);
+        TableFill timeModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
+        TableFill userModified = new TableFill("update_user", FieldFill.INSERT_UPDATE);
+        ArrayList<TableFill> tableFills = new ArrayList<>();
+        tableFills.add(deletedCreate);
+        tableFills.add(timeCreate);
+        tableFills.add(userCreate);
+        tableFills.add(timeModified);
+        tableFills.add(userModified);
+        strategy.setTableFillList(tableFills);
+        // 乐观锁
+        strategy.setVersionFieldName("version");
+        strategy.setRestControllerStyle(true);
+        strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
+        mpg.setStrategy(strategy);
+        mpg.execute(); //执行
+    }
+}

+ 19 - 19
src/main/java/com/template/MybatisPlusApplication.java

@@ -1,19 +1,19 @@
-package com.template;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-@EnableCaching//开启缓存
-@SpringBootApplication
-@EnableTransactionManagement //开启事务回滚
-@EnableScheduling // 开启定时任务
-public class MybatisPlusApplication {
-
-    public static void main(String[] args) {
-
-        SpringApplication.run(MybatisPlusApplication.class, args);
-    }
-}
+package com.template;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+@EnableCaching//开启缓存
+@SpringBootApplication
+@EnableTransactionManagement //开启事务回滚
+@EnableScheduling // 开启定时任务
+public class MybatisPlusApplication {
+
+    public static void main(String[] args) {
+
+        SpringApplication.run(MybatisPlusApplication.class, args);
+    }
+}

+ 12 - 12
src/main/java/com/template/annotation/ControllerIsShow.java

@@ -1,12 +1,12 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target(value = {ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ControllerIsShow {
-    String value() default "";
-}
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(value = {ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ControllerIsShow {
+    String value() default "";
+}

+ 17 - 17
src/main/java/com/template/annotation/DESRespondSecret.java

@@ -1,17 +1,17 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * 返回参数加密注解
- */
-
-//可以作用在类上和方法上
-@Target(value = {ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface DESRespondSecret {
-    boolean validated() default true;
-}
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * 返回参数加密注解
+ */
+
+//可以作用在类上和方法上
+@Target(value = {ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface DESRespondSecret {
+    boolean validated() default true;
+}

+ 18 - 18
src/main/java/com/template/annotation/ExcelExport.java

@@ -1,18 +1,18 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ElementType.FIELD})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ExcelExport {
-    String value();
-
-    int sort() default 0;
-
-    String kv() default "";
-
-    String example() default "";
-}
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.FIELD})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ExcelExport {
+    String value();
+
+    int sort() default 0;
+
+    String kv() default "";
+
+    String example() default "";
+}

+ 19 - 19
src/main/java/com/template/annotation/ExcelImport.java

@@ -1,20 +1,20 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ElementType.FIELD})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ExcelImport {
-    String value();
-
-    String kv() default "";
-
-    boolean required() default false;
-
-    int maxLength() default 255;
-
-    boolean unique() default false;
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.FIELD})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ExcelImport {
+    String value();
+
+    String kv() default "";
+
+    boolean required() default false;
+
+    int maxLength() default 255;
+
+    boolean unique() default false;
 }

+ 28 - 28
src/main/java/com/template/annotation/PassToken.java

@@ -1,28 +1,28 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/** 说明
- * 在方法上加入本注解 即可接口拦截
- * @interface:代表当前类是注解
- * @Target:描述当前的注解可以定义在扫描资源上。
- * 属性value:
- *     定义具体的资源。包括:
- *     ElementType.METHOD:可以定义在方法上
- *     ElementType.TYPE:可以定义在类上
- *     ElementType.FIELD:可以定义在属性上
- *     ElementType.PARAMETER:可以定义在方法参数上
- * @Retention:当前注解在什么时候有效
- *     定义具体的生效标记
- *     RetentionPolicy.RUNTIME:运行时有效
- *     RetentionPolicy.SOURCE:源码中有效
- *     RetentionPolicy.CLASS:字节码有效
- *///说明 该注解要加在控制器中的方法上才会生效 加在api中无法生效
-@Target(value = {ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface PassToken {
-    boolean requeired() default true;
-}
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/** 说明
+ * 在方法上加入本注解 即可接口拦截
+ * @interface:代表当前类是注解
+ * @Target:描述当前的注解可以定义在扫描资源上。
+ * 属性value:
+ *     定义具体的资源。包括:
+ *     ElementType.METHOD:可以定义在方法上
+ *     ElementType.TYPE:可以定义在类上
+ *     ElementType.FIELD:可以定义在属性上
+ *     ElementType.PARAMETER:可以定义在方法参数上
+ * @Retention:当前注解在什么时候有效
+ *     定义具体的生效标记
+ *     RetentionPolicy.RUNTIME:运行时有效
+ *     RetentionPolicy.SOURCE:源码中有效
+ *     RetentionPolicy.CLASS:字节码有效
+ *///说明 该注解要加在控制器中的方法上才会生效 加在api中无法生效
+@Target(value = {ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface PassToken {
+    boolean requeired() default true;
+}

+ 14 - 14
src/main/java/com/template/annotation/UserLoginCheck.java

@@ -1,14 +1,14 @@
-package com.template.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Target;
-
-/**
- * @Author: binguo
- * @Date: 2023/4/10 星期一 14:04
- * @Description: com.video.services.annotation
- * @Version: 1.0
- */
-@Target(ElementType.METHOD)
-public @interface UserLoginCheck {
-}
+package com.template.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/4/10 星期一 14:04
+ * @Description: com.video.services.annotation
+ * @Version: 1.0
+ */
+@Target(ElementType.METHOD)
+public @interface UserLoginCheck {
+}

+ 95 - 95
src/main/java/com/template/aop/DESResponseSecretAspect.java

@@ -1,95 +1,95 @@
-package com.template.aop;
-
-import com.alibaba.fastjson.JSON;
-import com.template.annotation.DESRespondSecret;
-import com.template.common.utils.EncryptUtil;
-import com.template.model.result.CommonResult;
-import org.aspectj.lang.JoinPoint;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.AfterReturning;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Pointcut;
-import org.aspectj.lang.reflect.MethodSignature;
-import org.springframework.stereotype.Component;
-
-import java.lang.reflect.Method;
-
-/**
- * @Author: binguo
- * @Date: 2024/2/26 星期一 10:02
- * @Description: com.template.aop
- * @Version: 1.0
- */
-@Component
-@Aspect
-//规定AOP的执行顺序
-//Order(1) 多个aop时可通过该注解来确定执行顺序
-public class DESResponseSecretAspect {
-
-    // 定义切点,使用了@DESRespondSecret注解的类 或 使用了@DESRespondSecret注解的方法
-
-    /**
-     * 切点,方法上有注解或类上有注解
-     * 拦截类或者是方法上标注注解的方法
-     */
-    @Pointcut("@within(com.template.annotation.DESRespondSecret) || @annotation(com.template.annotation.DESRespondSecret)")
-    public void pointCut() {
-    }
-
-    @Around("pointCut()")
-    public Object after(ProceedingJoinPoint joinPoint) throws Throwable {
-        Object rvt = joinPoint.proceed(joinPoint.getArgs());
-        return rvt;
-    }
-
-    /**
-     * 与After的区别在于AfterReturning只有在方法执行成功之后才会被植入,如果After和
-     * AfterReturning同时存在于一个文件中,谁写在前面谁先运行
-     *
-     * @param joinpoint
-     * @param rvt
-     * @return
-     */
-    @AfterReturning(pointcut = "execution(public * com.template.controller.*.*(..))", returning = "rvt")
-    public Object log(JoinPoint joinpoint, Object rvt) {
-        //获取被代理对象
-        Object target = joinpoint.getTarget();
-        //获取通知签名 获取方法上的DESRespondSecret注解
-        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
-        try {
-            // 获取被代理方法
-            Method pointMethod = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
-            // 获取被代理方法上面的注解@DESRespondSecret
-            DESRespondSecret secret = pointMethod.getAnnotation(DESRespondSecret.class);
-            // 被代理方法上没有,则说明@DESRespondSecret注解在被代理类上
-            if (secret == null) {
-                secret = target.getClass().getAnnotation(DESRespondSecret.class);
-            }
-            //类上也没有 直接返回
-            if (secret == null) {
-                return rvt;
-            }
-            // 如果有,并且值为false,则不进行加密
-            if (secret != null && !secret.validated()) {
-                return rvt;
-            } else {
-                CommonResult baseVo1 = (CommonResult) rvt;
-                // 获取返回值json字符串
-                Object data = baseVo1.getData();
-                if (null != data) {
-                    String jsonString = JSON.toJSONString(data);
-                    // 加密
-                    String s = EncryptUtil.encrypt(jsonString);
-                    baseVo1.setData(s);
-                }
-                return baseVo1;
-
-            }
-        } catch (Throwable throwable) {
-            throwable.printStackTrace();
-        }
-        return rvt;
-    }
-
-}
+package com.template.aop;
+
+import com.alibaba.fastjson.JSON;
+import com.template.annotation.DESRespondSecret;
+import com.template.common.utils.EncryptUtil;
+import com.template.model.result.CommonResult;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+
+/**
+ * @Author: binguo
+ * @Date: 2024/2/26 星期一 10:02
+ * @Description: com.template.aop
+ * @Version: 1.0
+ */
+@Component
+@Aspect
+//规定AOP的执行顺序
+//Order(1) 多个aop时可通过该注解来确定执行顺序
+public class DESResponseSecretAspect {
+
+    // 定义切点,使用了@DESRespondSecret注解的类 或 使用了@DESRespondSecret注解的方法
+
+    /**
+     * 切点,方法上有注解或类上有注解
+     * 拦截类或者是方法上标注注解的方法
+     */
+    @Pointcut("@within(com.template.annotation.DESRespondSecret) || @annotation(com.template.annotation.DESRespondSecret)")
+    public void pointCut() {
+    }
+
+    @Around("pointCut()")
+    public Object after(ProceedingJoinPoint joinPoint) throws Throwable {
+        Object rvt = joinPoint.proceed(joinPoint.getArgs());
+        return rvt;
+    }
+
+    /**
+     * 与After的区别在于AfterReturning只有在方法执行成功之后才会被植入,如果After和
+     * AfterReturning同时存在于一个文件中,谁写在前面谁先运行
+     *
+     * @param joinpoint
+     * @param rvt
+     * @return
+     */
+    @AfterReturning(pointcut = "execution(public * com.template.controller.*.*(..))", returning = "rvt")
+    public Object log(JoinPoint joinpoint, Object rvt) {
+        //获取被代理对象
+        Object target = joinpoint.getTarget();
+        //获取通知签名 获取方法上的DESRespondSecret注解
+        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
+        try {
+            // 获取被代理方法
+            Method pointMethod = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
+            // 获取被代理方法上面的注解@DESRespondSecret
+            DESRespondSecret secret = pointMethod.getAnnotation(DESRespondSecret.class);
+            // 被代理方法上没有,则说明@DESRespondSecret注解在被代理类上
+            if (secret == null) {
+                secret = target.getClass().getAnnotation(DESRespondSecret.class);
+            }
+            //类上也没有 直接返回
+            if (secret == null) {
+                return rvt;
+            }
+            // 如果有,并且值为false,则不进行加密
+            if (secret != null && !secret.validated()) {
+                return rvt;
+            } else {
+                CommonResult baseVo1 = (CommonResult) rvt;
+                // 获取返回值json字符串
+                Object data = baseVo1.getData();
+                if (null != data) {
+                    String jsonString = JSON.toJSONString(data);
+                    // 加密
+                    String s = EncryptUtil.encrypt(jsonString);
+                    baseVo1.setData(s);
+                }
+                return baseVo1;
+
+            }
+        } catch (Throwable throwable) {
+            throwable.printStackTrace();
+        }
+        return rvt;
+    }
+
+}

+ 45 - 45
src/main/java/com/template/aop/LoginCheckAspect.java

@@ -1,45 +1,45 @@
-package com.template.aop;
-
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.After;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Before;
-import org.springframework.core.annotation.Order;
-import org.springframework.stereotype.Component;
-
-/**
- * @Author: binguo
- * @Date: 2023/4/10 星期一 14:10
- * @Description: com.video.aop
- * @Version: 1.0
- */
-@Aspect//把当前类标识作为一个切面供容器读取
-@Component//将此类标记为Spring容器中的一个Bean
-@Order(0)//order的值越小,优先级越高 order如果不标注数字,默认最低优先级,因为其默认值是int最大值
-public class LoginCheckAspect {
-
-    @Around("@annotation(com.template.annotation.UserLoginCheck)")
-    public Object userLoginCheck(ProceedingJoinPoint process) throws Throwable {
-        System.out.println("用户登录检测机制");
-        if(1 == 1){
-           //通过抛异常方式拦截
-           // throw new Exception("非法登录");
-        }
-
-        Object proceed;
-        proceed = process.proceed();//执行目标方法
-        return proceed;//将执行目标方法后的返回值返回出去
-    }
-
-    @After("@annotation(com.template.annotation.UserLoginCheck)")
-    public void test(){
-        System.out.println("测试After");
-    }
-
-    @Before("@annotation(com.template.annotation.UserLoginCheck)")
-    public void test1(){
-        System.out.println("测试Before");
-    }
-
-}
+package com.template.aop;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.After;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Before;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/4/10 星期一 14:10
+ * @Description: com.video.aop
+ * @Version: 1.0
+ */
+@Aspect//把当前类标识作为一个切面供容器读取
+@Component//将此类标记为Spring容器中的一个Bean
+@Order(0)//order的值越小,优先级越高 order如果不标注数字,默认最低优先级,因为其默认值是int最大值
+public class LoginCheckAspect {
+
+    @Around("@annotation(com.template.annotation.UserLoginCheck)")
+    public Object userLoginCheck(ProceedingJoinPoint process) throws Throwable {
+        System.out.println("用户登录检测机制");
+        if(1 == 1){
+           //通过抛异常方式拦截
+           // throw new Exception("非法登录");
+        }
+
+        Object proceed;
+        proceed = process.proceed();//执行目标方法
+        return proceed;//将执行目标方法后的返回值返回出去
+    }
+
+    @After("@annotation(com.template.annotation.UserLoginCheck)")
+    public void test(){
+        System.out.println("测试After");
+    }
+
+    @Before("@annotation(com.template.annotation.UserLoginCheck)")
+    public void test1(){
+        System.out.println("测试Before");
+    }
+
+}

+ 49 - 49
src/main/java/com/template/api/BookingControllerAPI.java

@@ -1,49 +1,49 @@
-package com.template.api;
-
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/booking")
-@Api(tags = {"BookingController"}, value = "民宿定单接口")
-public interface BookingControllerAPI {
-    @GetMapping(value = "/QueryBookingTotal")
-    @ApiOperation(value = "住宿统计", notes = "住宿统计", httpMethod = "GET")
-    CommonResult QueryBookingTotal();
-
-    @GetMapping(value = "/QueryBookingTrend")
-    @ApiOperation(value = "7天预定趋势", notes = "7天预定趋势", httpMethod = "GET")
-    CommonResult QueryBookingTrend();
-
-    @GetMapping(value = "/QueryBookingAvgPrice")
-    @ApiOperation(value = "7天平均价格", notes = "7天平均价格", httpMethod = "GET")
-    CommonResult QueryBookingAvgPrice();
-
-    @GetMapping(value = "/QueryOrderRank")
-    @ApiOperation(value = "定单量排行", notes = "定单量排行", httpMethod = "GET")
-    CommonResult QueryOrderRank();
-
-    @GetMapping(value = "/getCommentAvg")
-    @ApiOperation(value = "评分百分比", notes = "评分百分比", httpMethod = "GET")
-    CommonResult getCommentAvg();
-
-
-    @GetMapping(value = "/getCommentInfo")
-    @ApiOperation(value = "评分详情", notes = "评分详情", httpMethod = "GET")
-    CommonResult getCommentInfo(String name,String startTime,String endTime,String flag,int pageNum,int pageSize);
-
-}
+package com.template.api;
+
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/booking")
+@Api(tags = {"BookingController"}, value = "民宿定单接口")
+public interface BookingControllerAPI {
+    @GetMapping(value = "/QueryBookingTotal")
+    @ApiOperation(value = "住宿统计", notes = "住宿统计", httpMethod = "GET")
+    CommonResult QueryBookingTotal();
+
+    @GetMapping(value = "/QueryBookingTrend")
+    @ApiOperation(value = "7天预定趋势", notes = "7天预定趋势", httpMethod = "GET")
+    CommonResult QueryBookingTrend();
+
+    @GetMapping(value = "/QueryBookingAvgPrice")
+    @ApiOperation(value = "7天平均价格", notes = "7天平均价格", httpMethod = "GET")
+    CommonResult QueryBookingAvgPrice();
+
+    @GetMapping(value = "/QueryOrderRank")
+    @ApiOperation(value = "定单量排行", notes = "定单量排行", httpMethod = "GET")
+    CommonResult QueryOrderRank();
+
+    @GetMapping(value = "/getCommentAvg")
+    @ApiOperation(value = "评分百分比", notes = "评分百分比", httpMethod = "GET")
+    CommonResult getCommentAvg();
+
+
+    @GetMapping(value = "/getCommentInfo")
+    @ApiOperation(value = "评分详情", notes = "评分详情", httpMethod = "GET")
+    CommonResult getCommentInfo(String name,String startTime,String endTime,String flag,int pageNum,int pageSize);
+
+}

+ 27 - 27
src/main/java/com/template/api/CateringControllerAPI.java

@@ -1,27 +1,27 @@
-package com.template.api;
-
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.List;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/catering")
-@Api(tags = {"CateringController"}, value = "餐饮接口")
-public interface CateringControllerAPI {
-
-    @GetMapping("/getTotal")
-    @ApiOperation(value = "查询", notes = "查询", httpMethod = "GET")
-    CommonResult getTotal();
-}
+package com.template.api;
+
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/catering")
+@Api(tags = {"CateringController"}, value = "餐饮接口")
+public interface CateringControllerAPI {
+
+    @GetMapping("/getTotal")
+    @ApiOperation(value = "查询", notes = "查询", httpMethod = "GET")
+    CommonResult getTotal();
+}

+ 18 - 18
src/main/java/com/template/api/ExcelControllerAPI.java

@@ -1,18 +1,18 @@
-package com.template.api;
-
-import com.template.annotation.PassToken;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-@Api(tags = {"ExcelController"}, value = "导入excel表")
-@RequestMapping("/api/excel")
-public interface ExcelControllerAPI {
-
-    @PostMapping("/toExcel")
-    @ApiOperation(value = "导入excel表更新用户",httpMethod = "POST")
-    @PassToken
-    void toExcel(String fileUrl);
-
-}
+package com.template.api;
+
+import com.template.annotation.PassToken;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Api(tags = {"ExcelController"}, value = "导入excel表")
+@RequestMapping("/api/excel")
+public interface ExcelControllerAPI {
+
+    @PostMapping("/toExcel")
+    @ApiOperation(value = "导入excel表更新用户",httpMethod = "POST")
+    @PassToken
+    void toExcel(String fileUrl);
+
+}

+ 36 - 36
src/main/java/com/template/api/HotelControllerAPI.java

@@ -1,36 +1,36 @@
-package com.template.api;
-
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.List;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/hotel")
-@Api(tags = {"HotelController"}, value = "民宿接口")
-public interface HotelControllerAPI {
-
-
-    @GetMapping("/QueryTownRate")
-    @ApiOperation(value = "查询民宿占比", notes = "查询民宿占比", httpMethod = "GET")
-    CommonResult QueryTownRate();
-
-    @GetMapping("/QueryHotelList")
-    @ApiOperation(value = "条件查询民宿列表", notes = "查询民宿列表", httpMethod = "GET")
-    CommonResult QueryHotelList(@RequestParam("town") String town,@RequestParam("hName")String hName,int pageNum,int pageSize);
-
-    @GetMapping("/QueryHotelListByName")
-    @ApiOperation(value = "根据名称查询民宿列表", notes = "根据名称查询民宿列表", httpMethod = "GET")
-    CommonResult QueryHotelListByName(@RequestParam("hName")String hName);
-}
+package com.template.api;
+
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/hotel")
+@Api(tags = {"HotelController"}, value = "民宿接口")
+public interface HotelControllerAPI {
+
+
+    @GetMapping("/QueryTownRate")
+    @ApiOperation(value = "查询民宿占比", notes = "查询民宿占比", httpMethod = "GET")
+    CommonResult QueryTownRate();
+
+    @GetMapping("/QueryHotelList")
+    @ApiOperation(value = "条件查询民宿列表", notes = "查询民宿列表", httpMethod = "GET")
+    CommonResult QueryHotelList(@RequestParam("town") String town,@RequestParam("hName")String hName,int pageNum,int pageSize);
+
+    @GetMapping("/QueryHotelListByName")
+    @ApiOperation(value = "根据名称查询民宿列表", notes = "根据名称查询民宿列表", httpMethod = "GET")
+    CommonResult QueryHotelListByName(@RequestParam("hName")String hName);
+}

+ 21 - 21
src/main/java/com/template/api/LogInfoControllerAPI.java

@@ -1,21 +1,21 @@
-package com.template.api;
-
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-@Api(tags = {"LogInfoController"}, value = "登入接口")
-@RequestMapping("/api/logInfo")
-public interface LogInfoControllerAPI {
-
-    @GetMapping("/verify")
-    @ApiOperation(value = "验证手机号phone",httpMethod = "GET")
-    CommonResult verifyPhone(String phone);
-
-
-    @PostMapping("/logIn")
-    @ApiOperation(value = "短信验证",httpMethod = "POST")
-    CommonResult logInfo(String phone,String code);
-}
+package com.template.api;
+
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+@Api(tags = {"LogInfoController"}, value = "登入接口")
+@RequestMapping("/api/logInfo")
+public interface LogInfoControllerAPI {
+
+    @GetMapping("/verify")
+    @ApiOperation(value = "验证手机号phone",httpMethod = "GET")
+    CommonResult verifyPhone(String phone);
+
+
+    @PostMapping("/logIn")
+    @ApiOperation(value = "短信验证",httpMethod = "POST")
+    CommonResult logInfo(String phone,String code);
+}

+ 34 - 34
src/main/java/com/template/api/LoginControllerAPI.java

@@ -1,34 +1,34 @@
-package com.template.api;
-
-import com.template.model.pojo.RepairAdmin;
-import com.template.model.request.loginRequest;
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.validation.BindingResult;
-import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.*;
-
-import javax.validation.Valid;
-
-
-@RequestMapping("/api/login")
-@Api(tags = {"LoginController"}, value = "登录")
-public interface LoginControllerAPI {
-
-    @GetMapping(value = "/queryReduce")
-    @ApiOperation(value = "查看系统版本", notes = "查看系统版本", httpMethod = "GET")
-    CommonResult queryReduce();
-
-    @PostMapping(value = "/Register")
-    @ApiOperation(value = "注册", notes = "注册", httpMethod = "POST")
-    CommonResult Register(@Validated @RequestBody RepairAdmin loginRequest, BindingResult bindingResult);
-
-    @PostMapping(value = "/Login")
-    @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST")
-    CommonResult Login(@Validated @RequestBody loginRequest lr, BindingResult bindingResult);
-
-    @PostMapping(value = "/ChangePassword")
-    @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST")
-    CommonResult ChangePassword(@Validated @RequestBody com.repair.model.request.changePasswordRequest cpr, @RequestHeader("user_head") String userhead, BindingResult bindingResult);
-}
+package com.template.api;
+
+import com.template.model.pojo.RepairAdmin;
+import com.template.model.request.loginRequest;
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+
+import javax.validation.Valid;
+
+
+@RequestMapping("/api/login")
+@Api(tags = {"LoginController"}, value = "登录")
+public interface LoginControllerAPI {
+
+    @GetMapping(value = "/queryReduce")
+    @ApiOperation(value = "查看系统版本", notes = "查看系统版本", httpMethod = "GET")
+    CommonResult queryReduce();
+
+    @PostMapping(value = "/Register")
+    @ApiOperation(value = "注册", notes = "注册", httpMethod = "POST")
+    CommonResult Register(@Validated @RequestBody RepairAdmin loginRequest, BindingResult bindingResult);
+
+    @PostMapping(value = "/Login")
+    @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST")
+    CommonResult Login(@Validated @RequestBody loginRequest lr, BindingResult bindingResult);
+
+    @PostMapping(value = "/ChangePassword")
+    @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST")
+    CommonResult ChangePassword(@Validated @RequestBody com.repair.model.request.changePasswordRequest cpr, @RequestHeader("user_head") String userhead, BindingResult bindingResult);
+}

+ 45 - 45
src/main/java/com/template/api/ParkingControllerAPI.java

@@ -1,45 +1,45 @@
-package com.template.api;
-
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/parking")
-@Api(tags = {"ParkingController"}, value = "停车场接口")
-public interface ParkingControllerAPI {
-
-
-    @GetMapping("/getParkingCount")
-    @ApiOperation(value = "查询停车场数量", notes = "查询停车场数量", httpMethod = "GET")
-    CommonResult getParkingCount();
-
-
-    @GetMapping("/getParkingSpace")
-    @ApiOperation(value = "查询停车场车位", notes = "查询停车场车位", httpMethod = "GET")
-    CommonResult getParkingSpace();
-
-    @GetMapping("/getParkingByTown")
-    @ApiOperation(value = "查询乡镇分布情况", notes = "查询乡镇分布情况", httpMethod = "GET")
-    CommonResult getParkingByTown();
-
-    @GetMapping("/getAllParkingInfo")
-    @ApiOperation(value = "查询停车场基本列表", notes = "查询停车场基本列表", httpMethod = "GET")
-    CommonResult getAllParkingInfo();
-
-    @GetMapping("/getParkingInfoById")
-    @ApiOperation(value = "根据id查询停车场详细信息", notes = "根据id查询停车场详细信息", httpMethod = "GET")
-    CommonResult getParkingInfoById(String id);
-
-    @GetMapping("/getParkingInfoByTime")
-    @ApiOperation(value = "同步停车场实时数据", notes = "同步停车场实时数据", httpMethod = "GET")
-    CommonResult getParkingInfoByTime(String dayId);
-}
+package com.template.api;
+
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/parking")
+@Api(tags = {"ParkingController"}, value = "停车场接口")
+public interface ParkingControllerAPI {
+
+
+    @GetMapping("/getParkingCount")
+    @ApiOperation(value = "查询停车场数量", notes = "查询停车场数量", httpMethod = "GET")
+    CommonResult getParkingCount();
+
+
+    @GetMapping("/getParkingSpace")
+    @ApiOperation(value = "查询停车场车位", notes = "查询停车场车位", httpMethod = "GET")
+    CommonResult getParkingSpace();
+
+    @GetMapping("/getParkingByTown")
+    @ApiOperation(value = "查询乡镇分布情况", notes = "查询乡镇分布情况", httpMethod = "GET")
+    CommonResult getParkingByTown();
+
+    @GetMapping("/getAllParkingInfo")
+    @ApiOperation(value = "查询停车场基本列表", notes = "查询停车场基本列表", httpMethod = "GET")
+    CommonResult getAllParkingInfo();
+
+    @GetMapping("/getParkingInfoById")
+    @ApiOperation(value = "根据id查询停车场详细信息", notes = "根据id查询停车场详细信息", httpMethod = "GET")
+    CommonResult getParkingInfoById(String id);
+
+    @GetMapping("/getParkingInfoByTime")
+    @ApiOperation(value = "同步停车场实时数据", notes = "同步停车场实时数据", httpMethod = "GET")
+    CommonResult getParkingInfoByTime(String dayId);
+}

+ 35 - 35
src/main/java/com/template/api/RepairAdminControllerAPI.java

@@ -1,35 +1,35 @@
-package com.template.api;
-
-import com.template.model.pojo.RepairAdmin;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.validation.BindingResult;
-import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.*;
-
-@RequestMapping("/api/repairAdmin")
-@Api(tags = {"RepairAdminController"}, value = "账号")
-public interface RepairAdminControllerAPI {
-
-    @PostMapping(value = "/insertRepairAdmin")
-    @ApiOperation(value = "添加账号", notes = "添加账号数据", httpMethod = "POST")
-    CommonResult InsertRepairAdmin(@Validated @RequestBody RepairAdmin repairAdmin, BindingResult bindingResult);
-
-    @GetMapping(value = "/queryPageRepairAdmins")
-    @ApiOperation(value = "账号分页数据", notes = "账号分页数据", httpMethod = "POST")
-    CommonResult queryPageRepairAdmins(@RequestParam int currentPage, @RequestParam int pageCount, String account, String phone, String userName);
-
-    @PostMapping(value = "/freezeRepairAdminById")
-    @ApiOperation(value = "根据ID冻结指定账号", notes = "根据ID冻结指定账户", httpMethod = "POST")
-    CommonResult freezeRepairAdminById(@Validated @RequestBody com.repair.model.request.freezeRepairAdminRequest frar, BindingResult bindingResult);
-
-    @GetMapping(value = "/deleteRepairAdminById")
-    @ApiOperation(value = "根据ID删除指定账号", notes = "根据ID删除指定账号", httpMethod = "POST")
-    CommonResult deleteRepairAdminById(@RequestParam String id);
-
-    @PostMapping(value = "/updateRepairAdminById")
-    @ApiOperation(value = "编辑账号数据", notes = "编辑账号数据", httpMethod = "POST")
-    CommonResult updateRepairAdminById(@Validated @RequestBody com.repair.model.request.updateRepairAdminRequest ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult);
-}
+package com.template.api;
+
+import com.template.model.pojo.RepairAdmin;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+
+@RequestMapping("/api/repairAdmin")
+@Api(tags = {"RepairAdminController"}, value = "账号")
+public interface RepairAdminControllerAPI {
+
+    @PostMapping(value = "/insertRepairAdmin")
+    @ApiOperation(value = "添加账号", notes = "添加账号数据", httpMethod = "POST")
+    CommonResult InsertRepairAdmin(@Validated @RequestBody RepairAdmin repairAdmin, BindingResult bindingResult);
+
+    @GetMapping(value = "/queryPageRepairAdmins")
+    @ApiOperation(value = "账号分页数据", notes = "账号分页数据", httpMethod = "POST")
+    CommonResult queryPageRepairAdmins(@RequestParam int currentPage, @RequestParam int pageCount, String account, String phone, String userName);
+
+    @PostMapping(value = "/freezeRepairAdminById")
+    @ApiOperation(value = "根据ID冻结指定账号", notes = "根据ID冻结指定账户", httpMethod = "POST")
+    CommonResult freezeRepairAdminById(@Validated @RequestBody com.repair.model.request.freezeRepairAdminRequest frar, BindingResult bindingResult);
+
+    @GetMapping(value = "/deleteRepairAdminById")
+    @ApiOperation(value = "根据ID删除指定账号", notes = "根据ID删除指定账号", httpMethod = "POST")
+    CommonResult deleteRepairAdminById(@RequestParam String id);
+
+    @PostMapping(value = "/updateRepairAdminById")
+    @ApiOperation(value = "编辑账号数据", notes = "编辑账号数据", httpMethod = "POST")
+    CommonResult updateRepairAdminById(@Validated @RequestBody com.repair.model.request.updateRepairAdminRequest ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult);
+}

+ 16 - 16
src/main/java/com/template/api/SmsCodeControllerAPI.java

@@ -1,16 +1,16 @@
-package com.template.api;
-
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-@RequestMapping("/api/smsCode")
-@Api(tags = {"SmsCodeControllerAPI"}, value = "短信验证码")
-public interface SmsCodeControllerAPI {
-
-    @GetMapping(value = "/InsertSmsCode")
-    @ApiOperation(value = "新增Code", notes = "新增Code", httpMethod = "POST")
-    CommonResult InsertSmsCode();
-}
+package com.template.api;
+
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@RequestMapping("/api/smsCode")
+@Api(tags = {"SmsCodeControllerAPI"}, value = "短信验证码")
+public interface SmsCodeControllerAPI {
+
+    @GetMapping(value = "/InsertSmsCode")
+    @ApiOperation(value = "新增Code", notes = "新增Code", httpMethod = "POST")
+    CommonResult InsertSmsCode();
+}

+ 31 - 31
src/main/java/com/template/api/SpecialityControllerAPI.java

@@ -1,31 +1,31 @@
-package com.template.api;
-
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.List;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/speciality")
-@Api(tags = {"SpecialityController"}, value = "线上特产")
-public interface SpecialityControllerAPI {
-
-    @GetMapping("/getTopByAmount")
-    @ApiOperation(value = "查询当月销量", notes = "查询当月销量", httpMethod = "GET")
-    CommonResult getTopByAmount();
-
-    @GetMapping("/getMonthTrend")
-    @ApiOperation(value = "查询12个月销售额数据", notes = "查询12个月销售额数据", httpMethod = "GET")
-    CommonResult getMonthTrend();
-}
+package com.template.api;
+
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/speciality")
+@Api(tags = {"SpecialityController"}, value = "线上特产")
+public interface SpecialityControllerAPI {
+
+    @GetMapping("/getTopByAmount")
+    @ApiOperation(value = "查询当月销量", notes = "查询当月销量", httpMethod = "GET")
+    CommonResult getTopByAmount();
+
+    @GetMapping("/getMonthTrend")
+    @ApiOperation(value = "查询12个月销售额数据", notes = "查询12个月销售额数据", httpMethod = "GET")
+    CommonResult getMonthTrend();
+}

+ 50 - 50
src/main/java/com/template/api/SystemMenuControllerAPI.java

@@ -1,50 +1,50 @@
-package com.template.api;
-
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.*;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.List;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/systemMenu")
-@Api(tags = {"SystemMenuController"}, value = "测试接口")
-public interface SystemMenuControllerAPI {
-    @GetMapping(value = "/QueryPlaybackRecordBySql")
-    @ApiOperation(value = "通过sql获取数据", notes = "通过sql获取数据", httpMethod = "GET")
-    CommonResult<List<SystemMenuVo>> QueryPlaybackRecordBySql();
-
-    @GetMapping(value = "/QuerySystemMenus")
-    @ApiOperation(value = "查询所有菜单数据", notes = "查询所有菜单数据", httpMethod = "GET")
-    CommonResult<List<SystemMenu>> QueryPlaybackRecords();
-
-    @PostMapping(value = "/InsertSystemMenu")
-    @ApiOperation(value = "新增菜单数据", notes = "新增菜单数据", httpMethod = "POST")
-    CommonResult InsertSystemMenu(@RequestBody SystemMenu systemMenu);
-
-    @PostMapping(value = "/DeleteSystemMenu")
-    @ApiOperation(value = "新增菜单数据", notes = "新增菜单数据", httpMethod = "POST")
-    CommonResult DeleteSystemMenu(@RequestParam("userId") Integer userID);
-
-    @GetMapping(value = "/QueryMenuTrees")
-    @ApiOperation(value = "查询树形菜单数据", notes = "查询树形菜单数据", httpMethod = "GET")
-    CommonResult<List<SystemMenuTreeVo>> QueryMenuTreeRecords();
-
-    @PostMapping(value = "/InsertPlaybackRecord")
-    @ApiOperation(value = "新增", notes = "新增", httpMethod = "POST")
-    CommonResult<Integer> InsertPlaybackRecord(@RequestBody SystemMenu pb);
-
-    @GetMapping("/testQuery")
-    @ApiOperation(value = "查询", notes = "查询", httpMethod = "GET")
-    CommonResult<List<SystemMenu>> QueryPlaybackRecords(HttpServletRequest request);
-}
+package com.template.api;
+
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/systemMenu")
+@Api(tags = {"SystemMenuController"}, value = "测试接口")
+public interface SystemMenuControllerAPI {
+    @GetMapping(value = "/QueryPlaybackRecordBySql")
+    @ApiOperation(value = "通过sql获取数据", notes = "通过sql获取数据", httpMethod = "GET")
+    CommonResult<List<SystemMenuVo>> QueryPlaybackRecordBySql();
+
+    @GetMapping(value = "/QuerySystemMenus")
+    @ApiOperation(value = "查询所有菜单数据", notes = "查询所有菜单数据", httpMethod = "GET")
+    CommonResult<List<SystemMenu>> QueryPlaybackRecords();
+
+    @PostMapping(value = "/InsertSystemMenu")
+    @ApiOperation(value = "新增菜单数据", notes = "新增菜单数据", httpMethod = "POST")
+    CommonResult InsertSystemMenu(@RequestBody SystemMenu systemMenu);
+
+    @PostMapping(value = "/DeleteSystemMenu")
+    @ApiOperation(value = "新增菜单数据", notes = "新增菜单数据", httpMethod = "POST")
+    CommonResult DeleteSystemMenu(@RequestParam("userId") Integer userID);
+
+    @GetMapping(value = "/QueryMenuTrees")
+    @ApiOperation(value = "查询树形菜单数据", notes = "查询树形菜单数据", httpMethod = "GET")
+    CommonResult<List<SystemMenuTreeVo>> QueryMenuTreeRecords();
+
+    @PostMapping(value = "/InsertPlaybackRecord")
+    @ApiOperation(value = "新增", notes = "新增", httpMethod = "POST")
+    CommonResult<Integer> InsertPlaybackRecord(@RequestBody SystemMenu pb);
+
+    @GetMapping("/testQuery")
+    @ApiOperation(value = "查询", notes = "查询", httpMethod = "GET")
+    CommonResult<List<SystemMenu>> QueryPlaybackRecords(HttpServletRequest request);
+}

+ 37 - 37
src/main/java/com/template/api/ToiletBaseControllerAPI.java

@@ -1,37 +1,37 @@
-package com.template.api;
-
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/toiletBase")
-@Api(tags = {"ToiletBaseController"}, value = "厕所接口")
-public interface ToiletBaseControllerAPI {
-
-
-    @GetMapping("/getToiletBaseCount")
-    @ApiOperation(value = "查询厕所分类数量", notes = "查询厕所分类数量", httpMethod = "GET")
-    CommonResult getToiletBaseCount();
-
-
-    @GetMapping("/getToiletBaseInfo")
-    @ApiOperation(value = "查询厕所基本信息", notes = "查询厕所基本信息", httpMethod = "GET")
-    CommonResult getToiletBaseInfo();
-
-    @GetMapping("/getToiletRealTime")
-    @ApiOperation(value = "查询厕所实时信息", notes = "查询厕所实时信息", httpMethod = "GET")
-    CommonResult getToiletRealTime();
-
-    @GetMapping("/getToiletRealTimeById")
-    @ApiOperation(value = "根据id查询厕所实时信息", notes = "根据id查询厕所实时信息", httpMethod = "GET")
-    CommonResult getToiletRealTimeById(String toiletId);
-}
+package com.template.api;
+
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/toiletBase")
+@Api(tags = {"ToiletBaseController"}, value = "厕所接口")
+public interface ToiletBaseControllerAPI {
+
+
+    @GetMapping("/getToiletBaseCount")
+    @ApiOperation(value = "查询厕所分类数量", notes = "查询厕所分类数量", httpMethod = "GET")
+    CommonResult getToiletBaseCount();
+
+
+    @GetMapping("/getToiletBaseInfo")
+    @ApiOperation(value = "查询厕所基本信息", notes = "查询厕所基本信息", httpMethod = "GET")
+    CommonResult getToiletBaseInfo();
+
+    @GetMapping("/getToiletRealTime")
+    @ApiOperation(value = "查询厕所实时信息", notes = "查询厕所实时信息", httpMethod = "GET")
+    CommonResult getToiletRealTime();
+
+    @GetMapping("/getToiletRealTimeById")
+    @ApiOperation(value = "根据id查询厕所实时信息", notes = "根据id查询厕所实时信息", httpMethod = "GET")
+    CommonResult getToiletRealTimeById(String toiletId);
+}

+ 28 - 28
src/main/java/com/template/api/WarmSmokeControllerAPI.java

@@ -1,28 +1,28 @@
-package com.template.api;
-
-import com.template.model.result.CommonResult;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/30 星期四 17:28
- * @Description: com.video.api
- * @Version: 1.0
- */
-@RequestMapping("/api/toiletBase")
-@Api(tags = {"WarmSmokeController"}, value = "厕所接口")
-public interface WarmSmokeControllerAPI {
-
-
-    @GetMapping("/getWarmSmokeByPlace")
-    @ApiOperation(value = "根据地址查询烟雾报警", notes = "根据地址查询烟雾报警", httpMethod = "GET")
-    CommonResult getWarmSmokeByPlace(String place);
-
-    @GetMapping("/getWarmSmokeCount")
-    @ApiOperation(value = "查询烟雾报警数量", notes = "查询烟雾报警数量", httpMethod = "GET")
-    CommonResult getWarmSmokeCount();
-
-}
+package com.template.api;
+
+import com.template.model.result.CommonResult;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/30 星期四 17:28
+ * @Description: com.video.api
+ * @Version: 1.0
+ */
+@RequestMapping("/api/toiletBase")
+@Api(tags = {"WarmSmokeController"}, value = "厕所接口")
+public interface WarmSmokeControllerAPI {
+
+
+    @GetMapping("/getWarmSmokeByPlace")
+    @ApiOperation(value = "根据地址查询烟雾报警", notes = "根据地址查询烟雾报警", httpMethod = "GET")
+    CommonResult getWarmSmokeByPlace(String place);
+
+    @GetMapping("/getWarmSmokeCount")
+    @ApiOperation(value = "查询烟雾报警数量", notes = "查询烟雾报警数量", httpMethod = "GET")
+    CommonResult getWarmSmokeCount();
+
+}

+ 16 - 16
src/main/java/com/template/common/constanst/Constanst.java

@@ -1,16 +1,16 @@
-package com.template.common.constanst;
-
-/**
- * <p>Title: Constanst</p>
- * <p>Description: 系统所用到的常量 </p>
- * @author fengyong
- * @date 2018年9月7日
- */
-public class Constanst {
-	
-	/**
-	 * 自定义加密措施
-	 */
-	public static final String PWD_MD5 = "FeNG#@YOnG";
-
-}
+package com.template.common.constanst;
+
+/**
+ * <p>Title: Constanst</p>
+ * <p>Description: 系统所用到的常量 </p>
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+public class Constanst {
+	
+	/**
+	 * 自定义加密措施
+	 */
+	public static final String PWD_MD5 = "FeNG#@YOnG";
+
+}

+ 14 - 14
src/main/java/com/template/common/exception/EmsException.java

@@ -1,14 +1,14 @@
-package com.template.common.exception;
-
-import com.template.common.result.ResponseStatusEnum;
-
-/**
- * 处理异常,统一封装
- */
-public class EmsException {
-
-    public static void display(ResponseStatusEnum responseStatusEnum) {
-        throw new MyCustomException(responseStatusEnum);
-    }
-
-}
+package com.template.common.exception;
+
+import com.template.common.result.ResponseStatusEnum;
+
+/**
+ * 处理异常,统一封装
+ */
+public class EmsException {
+
+    public static void display(ResponseStatusEnum responseStatusEnum) {
+        throw new MyCustomException(responseStatusEnum);
+    }
+
+}

+ 199 - 199
src/main/java/com/template/common/exception/EmsExceptionHandler.java

@@ -1,199 +1,199 @@
-package com.template.common.exception;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.template.common.result.ResponseStatusEnum;
-import com.template.model.result.CommonResult;
-import org.mybatis.spring.MyBatisSystemException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.support.DefaultMessageSourceResolvable;
-import org.springframework.http.converter.HttpMessageNotReadableException;
-import org.springframework.validation.BindException;
-import org.springframework.validation.BindingResult;
-import org.springframework.validation.FieldError;
-import org.springframework.web.HttpRequestMethodNotSupportedException;
-import org.springframework.web.bind.MethodArgumentNotValidException;
-import org.springframework.web.bind.MissingServletRequestParameterException;
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import com.fasterxml.jackson.databind.exc.InvalidFormatException;
-import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
-
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintViolationException;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 统一异常拦截处理
- * 可以针对异常的类型进行捕获,然后返回json信息到前端
- */
-@ControllerAdvice
-public class EmsExceptionHandler {
-
-    //org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
-    final static Logger logger=LoggerFactory.getLogger(EmsExceptionHandler.class);
-
-    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
-    @ExceptionHandler(BindException.class)
-    @ResponseBody
-    public CommonResult BindExceptionHandler(BindException e) {
-        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
-        logger.error("错误信息",message);
-        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
-    }
-
-    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
-    @ExceptionHandler(ConstraintViolationException.class)
-    @ResponseBody
-    public CommonResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
-        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
-        logger.error("错误信息",message);
-        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
-    }
-
-    @ResponseBody
-    @ExceptionHandler(NullPointerException.class)
-    public CommonResult exception(NullPointerException e) {
-        e.printStackTrace();
-        //String error=e.getFieldError().getDefaultMessage();
-        logger.error("错误信息",e.fillInStackTrace());
-        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
-    }
-
-    @ExceptionHandler(Exception.class)
-    @ResponseBody
-    public CommonResult exception(Exception e) {
-        e.printStackTrace();
-        logger.error("错误信息",e.fillInStackTrace());
-        return CommonResult.fail(e.getMessage());
-    }
-
-    //mysql连接超时
-    @ExceptionHandler(MyBatisSystemException.class)
-    @ResponseBody
-    public CommonResult exception(MyBatisSystemException e) {
-        e.printStackTrace();
-        //String error=e.getFieldError().getDefaultMessage();
-        logger.error("错误信息",e.fillInStackTrace());
-        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_MYSQL_TIMEOUT_ERROR);
-    }
-
-    //请求方式错误
-    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
-    @ResponseBody
-    public CommonResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
-        e.printStackTrace();
-        logger.error("错误信息",e.fillInStackTrace());
-        //String error=e.getFieldError().getDefaultMessage();
-        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_REQUEST_METHOD_ERROR);
-    }
-
-    //传参空异常
-    @ExceptionHandler(MissingServletRequestParameterException.class)
-    @ResponseBody
-    public CommonResult missingServletRequestParameterException(MissingServletRequestParameterException e) {
-        String name=  e.getParameterName();
-        logger.error("错误信息",e.fillInStackTrace());
-
-        //String error=e.getFieldError().getDefaultMessage();
-        return CommonResult.fail(name+"不能为空");
-    }
-
-    @ExceptionHandler(MyCustomException.class)
-    @ResponseBody
-    public CommonResult returnMyException(MyCustomException e) {
-        e.printStackTrace();
-        logger.error("错误信息",e.fillInStackTrace());
-        return CommonResult.resultValue(e.getResponseStatusEnum());
-    }
-
-    /**
-     * 传入JSON数据格式错误
-     * @param e
-     * @return
-     */
-    @ExceptionHandler(JsonParseException.class)
-    @ResponseBody
-    public CommonResult returnMyException(JsonParseException e) {
-        logger.error("错误信息",e.fillInStackTrace());
-        e.printStackTrace();
-        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS);
-    }
-
-
-    /**
-     * 传入JSON数据格式转换错误
-     * @param e
-     * @return
-     */
-    @ExceptionHandler(HttpMessageNotReadableException.class)
-    @ResponseBody
-    public CommonResult httpMessageNotReadableException(HttpMessageNotReadableException e) {
-        logger.error("错误信息",e.fillInStackTrace());
-        e.printStackTrace();//
-        if(e.getCause() instanceof  InvalidFormatException){
-            InvalidFormatException e1=   (InvalidFormatException)e.getCause();
-            Object erro1= e1.getValue();
-            Object erro2=e1.getTargetType().getSimpleName();
-            System.out.print(erro1);
-            System.out.print(erro2);
-        }
-
-        String error=e.getMessage();
-        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS_TYPE);
-    }
-
-
-
-
-
-
-
-    /**
-     * 参数验证错误
-     * @param e
-     * @return
-     */
-    @ExceptionHandler(MethodArgumentNotValidException.class)
-    @ResponseBody
-    public CommonResult returnException(MethodArgumentNotValidException e) {
-        logger.error("错误信息",e.fillInStackTrace());
-        BindingResult result = e.getBindingResult();
-        Map<String, String> map = getErrors(result);
-        return CommonResult.fail(map.values().toString().replace("[","").replace("]",""));
-    }
-
-    /**
-     * 参数验证错误
-     * @param e
-     * @return
-     */
-    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
-    @ResponseBody
-    public CommonResult returnException(MethodArgumentTypeMismatchException e) {
-        logger.error("错误信息",e.fillInStackTrace());
-        String value=e.getValue().toString();
-        String paraType=e.getRequiredType().getName().toString();
-
-        return CommonResult.errorMsg(e.getName()+"数据格式转换错误");
-    }
-
-
-    public Map<String, String> getErrors(BindingResult result) {
-        Map<String, String> map = new HashMap<>();
-        List<FieldError> errorList = result.getFieldErrors();
-        for (FieldError error : errorList) {
-            // 发送验证错误的时候所对应的某个属性
-            String field = error.getField();
-            // 验证的错误消息
-            String msg = error.getDefaultMessage();
-            map.put(field, msg);
-        }
-        return map;
-    }
-
-
-}
+package com.template.common.exception;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.template.common.result.ResponseStatusEnum;
+import com.template.model.result.CommonResult;
+import org.mybatis.spring.MyBatisSystemException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.support.DefaultMessageSourceResolvable;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.validation.BindException;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.FieldError;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.MissingServletRequestParameterException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import com.fasterxml.jackson.databind.exc.InvalidFormatException;
+import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.ConstraintViolationException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * 统一异常拦截处理
+ * 可以针对异常的类型进行捕获,然后返回json信息到前端
+ */
+@ControllerAdvice
+public class EmsExceptionHandler {
+
+    //org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
+    final static Logger logger=LoggerFactory.getLogger(EmsExceptionHandler.class);
+
+    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
+    @ExceptionHandler(BindException.class)
+    @ResponseBody
+    public CommonResult BindExceptionHandler(BindException e) {
+        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
+        logger.error("错误信息",message);
+        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
+    }
+
+    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
+    @ExceptionHandler(ConstraintViolationException.class)
+    @ResponseBody
+    public CommonResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
+        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
+        logger.error("错误信息",message);
+        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
+    }
+
+    @ResponseBody
+    @ExceptionHandler(NullPointerException.class)
+    public CommonResult exception(NullPointerException e) {
+        e.printStackTrace();
+        //String error=e.getFieldError().getDefaultMessage();
+        logger.error("错误信息",e.fillInStackTrace());
+        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_NULL_POINTER);
+    }
+
+    @ExceptionHandler(Exception.class)
+    @ResponseBody
+    public CommonResult exception(Exception e) {
+        e.printStackTrace();
+        logger.error("错误信息",e.fillInStackTrace());
+        return CommonResult.fail(e.getMessage());
+    }
+
+    //mysql连接超时
+    @ExceptionHandler(MyBatisSystemException.class)
+    @ResponseBody
+    public CommonResult exception(MyBatisSystemException e) {
+        e.printStackTrace();
+        //String error=e.getFieldError().getDefaultMessage();
+        logger.error("错误信息",e.fillInStackTrace());
+        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_MYSQL_TIMEOUT_ERROR);
+    }
+
+    //请求方式错误
+    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
+    @ResponseBody
+    public CommonResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
+        e.printStackTrace();
+        logger.error("错误信息",e.fillInStackTrace());
+        //String error=e.getFieldError().getDefaultMessage();
+        return CommonResult.resultValue(ResponseStatusEnum.SYSTEM_REQUEST_METHOD_ERROR);
+    }
+
+    //传参空异常
+    @ExceptionHandler(MissingServletRequestParameterException.class)
+    @ResponseBody
+    public CommonResult missingServletRequestParameterException(MissingServletRequestParameterException e) {
+        String name=  e.getParameterName();
+        logger.error("错误信息",e.fillInStackTrace());
+
+        //String error=e.getFieldError().getDefaultMessage();
+        return CommonResult.fail(name+"不能为空");
+    }
+
+    @ExceptionHandler(MyCustomException.class)
+    @ResponseBody
+    public CommonResult returnMyException(MyCustomException e) {
+        e.printStackTrace();
+        logger.error("错误信息",e.fillInStackTrace());
+        return CommonResult.resultValue(e.getResponseStatusEnum());
+    }
+
+    /**
+     * 传入JSON数据格式错误
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(JsonParseException.class)
+    @ResponseBody
+    public CommonResult returnMyException(JsonParseException e) {
+        logger.error("错误信息",e.fillInStackTrace());
+        e.printStackTrace();
+        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS);
+    }
+
+
+    /**
+     * 传入JSON数据格式转换错误
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(HttpMessageNotReadableException.class)
+    @ResponseBody
+    public CommonResult httpMessageNotReadableException(HttpMessageNotReadableException e) {
+        logger.error("错误信息",e.fillInStackTrace());
+        e.printStackTrace();//
+        if(e.getCause() instanceof  InvalidFormatException){
+            InvalidFormatException e1=   (InvalidFormatException)e.getCause();
+            Object erro1= e1.getValue();
+            Object erro2=e1.getTargetType().getSimpleName();
+            System.out.print(erro1);
+            System.out.print(erro2);
+        }
+
+        String error=e.getMessage();
+        return CommonResult.resultValue(ResponseStatusEnum.SEND_PARAMS_TYPE);
+    }
+
+
+
+
+
+
+
+    /**
+     * 参数验证错误
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(MethodArgumentNotValidException.class)
+    @ResponseBody
+    public CommonResult returnException(MethodArgumentNotValidException e) {
+        logger.error("错误信息",e.fillInStackTrace());
+        BindingResult result = e.getBindingResult();
+        Map<String, String> map = getErrors(result);
+        return CommonResult.fail(map.values().toString().replace("[","").replace("]",""));
+    }
+
+    /**
+     * 参数验证错误
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
+    @ResponseBody
+    public CommonResult returnException(MethodArgumentTypeMismatchException e) {
+        logger.error("错误信息",e.fillInStackTrace());
+        String value=e.getValue().toString();
+        String paraType=e.getRequiredType().getName().toString();
+
+        return CommonResult.errorMsg(e.getName()+"数据格式转换错误");
+    }
+
+
+    public Map<String, String> getErrors(BindingResult result) {
+        Map<String, String> map = new HashMap<>();
+        List<FieldError> errorList = result.getFieldErrors();
+        for (FieldError error : errorList) {
+            // 发送验证错误的时候所对应的某个属性
+            String field = error.getField();
+            // 验证的错误消息
+            String msg = error.getDefaultMessage();
+            map.put(field, msg);
+        }
+        return map;
+    }
+
+
+}

+ 29 - 29
src/main/java/com/template/common/exception/MyCustomException.java

@@ -1,29 +1,29 @@
-package com.template.common.exception;
-
-import com.template.common.result.ResponseStatusEnum;
-
-/**
- * 自定义异常
- * 目的:统一处理异常信息
- *      便于解耦,service与controller错误的解耦,不会被service返回的类型而限制
- */
-public class MyCustomException extends RuntimeException {
-
-    private ResponseStatusEnum responseStatusEnum;
-
-    public MyCustomException(ResponseStatusEnum responseStatusEnum) {
-        super("异常状态码为:" + responseStatusEnum.status()
-                + ";具体异常信息为:" + responseStatusEnum.msg());
-        this.responseStatusEnum = responseStatusEnum;
-    }
-
-    public ResponseStatusEnum getResponseStatusEnum() {
-        return responseStatusEnum;
-    }
-
-    public void setResponseStatusEnum(ResponseStatusEnum responseStatusEnum) {
-        this.responseStatusEnum = responseStatusEnum;
-    }
-
-
-}
+package com.template.common.exception;
+
+import com.template.common.result.ResponseStatusEnum;
+
+/**
+ * 自定义异常
+ * 目的:统一处理异常信息
+ *      便于解耦,service与controller错误的解耦,不会被service返回的类型而限制
+ */
+public class MyCustomException extends RuntimeException {
+
+    private ResponseStatusEnum responseStatusEnum;
+
+    public MyCustomException(ResponseStatusEnum responseStatusEnum) {
+        super("异常状态码为:" + responseStatusEnum.status()
+                + ";具体异常信息为:" + responseStatusEnum.msg());
+        this.responseStatusEnum = responseStatusEnum;
+    }
+
+    public ResponseStatusEnum getResponseStatusEnum() {
+        return responseStatusEnum;
+    }
+
+    public void setResponseStatusEnum(ResponseStatusEnum responseStatusEnum) {
+        this.responseStatusEnum = responseStatusEnum;
+    }
+
+
+}

+ 43 - 43
src/main/java/com/template/common/jh/ReqRespResearchProductQuestionnaireItem.java

@@ -1,43 +1,43 @@
-package com.template.common.jh;
-
-import java.io.Serializable;
-
-public class ReqRespResearchProductQuestionnaireItem implements Serializable {
-    private static final long serialVersionUID = -2850886454687095222L;
-    private String minValue;
-    private String maxValue;
-    //"范围符号:1-大于/2-小于/3-等于/4-不等于/5-大于等于/6-小于等于/7-全闭区间/8-左闭右开区间/9-左开右闭区间/10-全开区间"
-    private Byte symbol;
-
-    public ReqRespResearchProductQuestionnaireItem( String minValue, String maxValue, Byte symbol) {
-        this.minValue = minValue;
-        this.maxValue = maxValue;
-        this.symbol = symbol;
-    }
-
-    public String getMinValue() {
-        return minValue;
-    }
-
-    public void setMinValue(String minValue) {
-        this.minValue = minValue;
-    }
-
-    public String getMaxValue() {
-        return maxValue;
-    }
-
-    public void setMaxValue(String maxValue) {
-        this.maxValue = maxValue;
-    }
-
-    public Byte getSymbol() {
-        return symbol;
-    }
-
-    public void setSymbol(Byte symbol) {
-        this.symbol = symbol;
-    }
-}
-
-
+package com.template.common.jh;
+
+import java.io.Serializable;
+
+public class ReqRespResearchProductQuestionnaireItem implements Serializable {
+    private static final long serialVersionUID = -2850886454687095222L;
+    private String minValue;
+    private String maxValue;
+    //"范围符号:1-大于/2-小于/3-等于/4-不等于/5-大于等于/6-小于等于/7-全闭区间/8-左闭右开区间/9-左开右闭区间/10-全开区间"
+    private Byte symbol;
+
+    public ReqRespResearchProductQuestionnaireItem( String minValue, String maxValue, Byte symbol) {
+        this.minValue = minValue;
+        this.maxValue = maxValue;
+        this.symbol = symbol;
+    }
+
+    public String getMinValue() {
+        return minValue;
+    }
+
+    public void setMinValue(String minValue) {
+        this.minValue = minValue;
+    }
+
+    public String getMaxValue() {
+        return maxValue;
+    }
+
+    public void setMaxValue(String maxValue) {
+        this.maxValue = maxValue;
+    }
+
+    public Byte getSymbol() {
+        return symbol;
+    }
+
+    public void setSymbol(Byte symbol) {
+        this.symbol = symbol;
+    }
+}
+
+

+ 243 - 243
src/main/java/com/template/common/jh/SectionUtil.java

@@ -1,243 +1,243 @@
-package com.template.common.jh;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @description: 区间工具类
- * @author: wyj
- * @time: 2020/3/1 15:05
- */
-public class SectionUtil {
-    //最小值
-    private String min_entity;
-    //最大值
-    private String max_entity;
-    //左侧括号状态:false -开区间  true-- 闭区间
-    private boolean left_sate = false;
-    //右侧括号状态:false -开区间  true-- 闭区间
-    private boolean right_sate = false;
-    private SectionUtil() {
-
-    }
-
-    public SectionUtil(String min_entity, String max_entity, boolean left_sate, boolean right_sate) {
-        this.min_entity = min_entity;
-        this.max_entity = max_entity;
-        this.left_sate = left_sate;
-        this.right_sate = right_sate;
-    }
-
-    public String getMin_entity() {
-        return min_entity;
-    }
-
-    public String getMax_entity() {
-        return max_entity;
-    }
-
-    public boolean isLeft_sate() {
-        return left_sate;
-    }
-
-    public boolean isRight_sate() {
-        return right_sate;
-    }
-
-    /**
-     * @description: 创建负区间((负无穷,X])
-     * @param value 区间最大值
-     * @param right_sate 区间开闭状态
-     * @Date: 2020/3/2 14:37
-     */
-    public static SectionUtil creatFu(String value, boolean right_sate) {
-
-        return new SectionUtil("", value, false, right_sate);
-    }
-    /**
-     * @description: 创建正区间[X,正无穷))
-     * @param value 区间最小值
-     * @param left_sate 区间开闭状态
-     * @Date: 2020/3/2 14:37
-     */
-    public static SectionUtil creatZheng(String value, boolean left_sate) {
-
-        return new SectionUtil(value, "", left_sate, false);
-    }
-    /**
-     * @description: 创建闭合区间([X,Y])
-     * @param min   区间最小值
-     * @param max   区间最大值
-     * @param left_sate 区间左侧开闭状态
-     * @param right_sate 区间右侧开闭状态
-     * @return
-     * @Date: 2020/3/2 14:41
-     */
-    public static SectionUtil creat(String min, boolean left_sate, String max, boolean right_sate) {
-
-        return new SectionUtil(min, max, left_sate, right_sate);
-    }
-    /**
-     * @description:  将实体类转换成区间集合
-     * @param record  待转换的实体类
-     * @return 转换后的区间集合类(不等于时转换后为2个区间,所以采用集合)
-     * @Date: 2020/3/2 14:19
-     */
-    public static List<SectionUtil> getSections(ReqRespResearchProductQuestionnaireItem record) {
-        List<SectionUtil> list = new ArrayList<>();
-        String record_max = record.getMaxValue();
-        String record_min = record.getMinValue();
-        switch (record.getSymbol()) {
-            case 1:
-                list.add(creatZheng(record_max, false));
-                break;
-            case 2:
-                list.add(creatFu(record_max, false));
-                break;
-            case 3:
-                list.add(creat(record_max, true, record_max, true));
-                break;
-            case 4:
-                list.add(creatFu(record_max, false));
-                list.add(creatZheng(record_max, false));
-                break;
-            case 5:
-                list.add(creatZheng(record_max, true));
-                break;
-            case 6:
-                list.add(creatFu(record_max, true));
-                break;
-            case 7:
-                list.add(creat(record_min, true, record_max, true));
-                break;
-            case 8:
-                list.add(creat(record_min, true, record_max, false));
-                break;
-            case 9:
-                list.add(creat(record_min, false, record_max, true));
-                break;
-            case 10:
-                list.add(creat(record_min, false, record_max, false));
-                break;
-        }
-        return list;
-    }
-
-
-
-    public int compareTo(String first_value, String second_value) {
-        //first_value为空表示为正无穷,second_value为空表示为负无穷
-        if (isBlank(first_value) || isBlank(second_value)) {
-            return 1;
-        }
-        return compareToValue(first_value,second_value);
-    }
-    //判断字符串是否为空
-    public static boolean isBlank(String str) {
-        int strLen;
-        if (str == null || (strLen = str.length()) == 0) {
-            return true;
-        }
-        for (int i = 0; i < strLen; i++) {
-            if ((Character.isWhitespace(str.charAt(i)) == false)) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    /**
-     * @param record 判断区间是否有重合
-     * @return true-有重合  false -无重合
-     * @description: 判断当前区间是否和指定区间重合
-     * @Date: 2020/3/2 10:20
-     */
-    public boolean isChonghe(SectionUtil record) {
-        String min_entity = record.getMin_entity();
-        String max_entity = record.getMax_entity();
-        boolean left_sate = record.isLeft_sate();
-        boolean right_sate = record.isRight_sate();
-        boolean left_isok = false;
-        boolean right_isok = false;
-        //重合条件,第一个区间最大值大于第二个区间最小值并且第一个区间的最小值小于第二个区间的最大值
-        //注意传值顺序,第一个值为第一个区间的最大值(此处不能反)
-        int first_result = compareTo(this.max_entity, min_entity);
-        if ((first_result == 0 && this.right_sate && left_sate) || (first_result > 0)) {
-            left_isok = true;
-        }
-        //注意传值顺序,第一个值为第二个区间的最大值(此处不能反)
-        int second_result = compareTo(max_entity, this.min_entity);
-        //此处本应该是second_result<0,但由于上一步参数传递时时反正传递,故此此处为second_result>0
-        if ((second_result == 0 && this.left_sate && right_sate) || second_result > 0) {
-            right_isok = true;
-        }
-        return left_isok && right_isok;
-    }
-    /**
-     * @description:   比较集合中区间是否有重叠
-     * @param list1 待比较集合1
-     * @param list2 待比较集合2
-     * @return
-     * @Date: 2020/3/2 11:49
-     */
-    public static boolean isChonghe(List<SectionUtil> list1, List<SectionUtil> list2) {
-        boolean chonghed = false;
-        for (SectionUtil item1 : list1) {
-            for (SectionUtil item2 : list2) {
-                chonghed = item1.isChonghe(item2);
-                if (chonghed) {
-                    return true;
-                }
-            }
-        }
-        return chonghed;
-    }
-
-    //比较大小
-    public static int compareToValue(String value1, String value2) {
-        BigDecimal b1 = new BigDecimal(value1);
-        BigDecimal b2 = new BigDecimal(value2);
-        return b1.compareTo(b2);
-    }
-
-    /**
-     * @description:   判断集合中区间是否重叠
-     * @param list  待判断集合
-     * @return  fasle-无重叠 true-有重叠
-     * @Date: 2020/3/3 14:51
-     */
-    public static boolean compareSection(List<ReqRespResearchProductQuestionnaireItem> list) {
-        for (int i = 0; i < list.size(); i++) {
-            ReqRespResearchProductQuestionnaireItem record = list.get(i);
-            for (int j = i + 1; j < list.size(); j++) {
-                ReqRespResearchProductQuestionnaireItem item = list.get(j);
-                //判断区间是否有交叉
-                List<SectionUtil> records = SectionUtil.getSections(record);
-                List<SectionUtil> items = SectionUtil.getSections(item);
-                boolean chonghe = SectionUtil.isChonghe(records, items);
-                if (chonghe) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    public static void main(String[] args) {
-        List<ReqRespResearchProductQuestionnaireItem> all = new ArrayList<>();
-        ReqRespResearchProductQuestionnaireItem re1 = new ReqRespResearchProductQuestionnaireItem("110","120", (byte) 7);
-        ReqRespResearchProductQuestionnaireItem re2 = new ReqRespResearchProductQuestionnaireItem("90","112", (byte) 7);
-        ReqRespResearchProductQuestionnaireItem re3 = new ReqRespResearchProductQuestionnaireItem("80","89", (byte) 7);
-        ReqRespResearchProductQuestionnaireItem re4 = new ReqRespResearchProductQuestionnaireItem("60","79", (byte) 7);
-        ReqRespResearchProductQuestionnaireItem re5 = new ReqRespResearchProductQuestionnaireItem("0","59", (byte) 7);
-        all.add(re1);
-        all.add(re2);
-        all.add(re3);
-        all.add(re4);
-        all.add(re5);
-        System.out.println(compareSection(all));
-    }
-}
-
-
+package com.template.common.jh;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @description: 区间工具类
+ * @author: wyj
+ * @time: 2020/3/1 15:05
+ */
+public class SectionUtil {
+    //最小值
+    private String min_entity;
+    //最大值
+    private String max_entity;
+    //左侧括号状态:false -开区间  true-- 闭区间
+    private boolean left_sate = false;
+    //右侧括号状态:false -开区间  true-- 闭区间
+    private boolean right_sate = false;
+    private SectionUtil() {
+
+    }
+
+    public SectionUtil(String min_entity, String max_entity, boolean left_sate, boolean right_sate) {
+        this.min_entity = min_entity;
+        this.max_entity = max_entity;
+        this.left_sate = left_sate;
+        this.right_sate = right_sate;
+    }
+
+    public String getMin_entity() {
+        return min_entity;
+    }
+
+    public String getMax_entity() {
+        return max_entity;
+    }
+
+    public boolean isLeft_sate() {
+        return left_sate;
+    }
+
+    public boolean isRight_sate() {
+        return right_sate;
+    }
+
+    /**
+     * @description: 创建负区间((负无穷,X])
+     * @param value 区间最大值
+     * @param right_sate 区间开闭状态
+     * @Date: 2020/3/2 14:37
+     */
+    public static SectionUtil creatFu(String value, boolean right_sate) {
+
+        return new SectionUtil("", value, false, right_sate);
+    }
+    /**
+     * @description: 创建正区间[X,正无穷))
+     * @param value 区间最小值
+     * @param left_sate 区间开闭状态
+     * @Date: 2020/3/2 14:37
+     */
+    public static SectionUtil creatZheng(String value, boolean left_sate) {
+
+        return new SectionUtil(value, "", left_sate, false);
+    }
+    /**
+     * @description: 创建闭合区间([X,Y])
+     * @param min   区间最小值
+     * @param max   区间最大值
+     * @param left_sate 区间左侧开闭状态
+     * @param right_sate 区间右侧开闭状态
+     * @return
+     * @Date: 2020/3/2 14:41
+     */
+    public static SectionUtil creat(String min, boolean left_sate, String max, boolean right_sate) {
+
+        return new SectionUtil(min, max, left_sate, right_sate);
+    }
+    /**
+     * @description:  将实体类转换成区间集合
+     * @param record  待转换的实体类
+     * @return 转换后的区间集合类(不等于时转换后为2个区间,所以采用集合)
+     * @Date: 2020/3/2 14:19
+     */
+    public static List<SectionUtil> getSections(ReqRespResearchProductQuestionnaireItem record) {
+        List<SectionUtil> list = new ArrayList<>();
+        String record_max = record.getMaxValue();
+        String record_min = record.getMinValue();
+        switch (record.getSymbol()) {
+            case 1:
+                list.add(creatZheng(record_max, false));
+                break;
+            case 2:
+                list.add(creatFu(record_max, false));
+                break;
+            case 3:
+                list.add(creat(record_max, true, record_max, true));
+                break;
+            case 4:
+                list.add(creatFu(record_max, false));
+                list.add(creatZheng(record_max, false));
+                break;
+            case 5:
+                list.add(creatZheng(record_max, true));
+                break;
+            case 6:
+                list.add(creatFu(record_max, true));
+                break;
+            case 7:
+                list.add(creat(record_min, true, record_max, true));
+                break;
+            case 8:
+                list.add(creat(record_min, true, record_max, false));
+                break;
+            case 9:
+                list.add(creat(record_min, false, record_max, true));
+                break;
+            case 10:
+                list.add(creat(record_min, false, record_max, false));
+                break;
+        }
+        return list;
+    }
+
+
+
+    public int compareTo(String first_value, String second_value) {
+        //first_value为空表示为正无穷,second_value为空表示为负无穷
+        if (isBlank(first_value) || isBlank(second_value)) {
+            return 1;
+        }
+        return compareToValue(first_value,second_value);
+    }
+    //判断字符串是否为空
+    public static boolean isBlank(String str) {
+        int strLen;
+        if (str == null || (strLen = str.length()) == 0) {
+            return true;
+        }
+        for (int i = 0; i < strLen; i++) {
+            if ((Character.isWhitespace(str.charAt(i)) == false)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * @param record 判断区间是否有重合
+     * @return true-有重合  false -无重合
+     * @description: 判断当前区间是否和指定区间重合
+     * @Date: 2020/3/2 10:20
+     */
+    public boolean isChonghe(SectionUtil record) {
+        String min_entity = record.getMin_entity();
+        String max_entity = record.getMax_entity();
+        boolean left_sate = record.isLeft_sate();
+        boolean right_sate = record.isRight_sate();
+        boolean left_isok = false;
+        boolean right_isok = false;
+        //重合条件,第一个区间最大值大于第二个区间最小值并且第一个区间的最小值小于第二个区间的最大值
+        //注意传值顺序,第一个值为第一个区间的最大值(此处不能反)
+        int first_result = compareTo(this.max_entity, min_entity);
+        if ((first_result == 0 && this.right_sate && left_sate) || (first_result > 0)) {
+            left_isok = true;
+        }
+        //注意传值顺序,第一个值为第二个区间的最大值(此处不能反)
+        int second_result = compareTo(max_entity, this.min_entity);
+        //此处本应该是second_result<0,但由于上一步参数传递时时反正传递,故此此处为second_result>0
+        if ((second_result == 0 && this.left_sate && right_sate) || second_result > 0) {
+            right_isok = true;
+        }
+        return left_isok && right_isok;
+    }
+    /**
+     * @description:   比较集合中区间是否有重叠
+     * @param list1 待比较集合1
+     * @param list2 待比较集合2
+     * @return
+     * @Date: 2020/3/2 11:49
+     */
+    public static boolean isChonghe(List<SectionUtil> list1, List<SectionUtil> list2) {
+        boolean chonghed = false;
+        for (SectionUtil item1 : list1) {
+            for (SectionUtil item2 : list2) {
+                chonghed = item1.isChonghe(item2);
+                if (chonghed) {
+                    return true;
+                }
+            }
+        }
+        return chonghed;
+    }
+
+    //比较大小
+    public static int compareToValue(String value1, String value2) {
+        BigDecimal b1 = new BigDecimal(value1);
+        BigDecimal b2 = new BigDecimal(value2);
+        return b1.compareTo(b2);
+    }
+
+    /**
+     * @description:   判断集合中区间是否重叠
+     * @param list  待判断集合
+     * @return  fasle-无重叠 true-有重叠
+     * @Date: 2020/3/3 14:51
+     */
+    public static boolean compareSection(List<ReqRespResearchProductQuestionnaireItem> list) {
+        for (int i = 0; i < list.size(); i++) {
+            ReqRespResearchProductQuestionnaireItem record = list.get(i);
+            for (int j = i + 1; j < list.size(); j++) {
+                ReqRespResearchProductQuestionnaireItem item = list.get(j);
+                //判断区间是否有交叉
+                List<SectionUtil> records = SectionUtil.getSections(record);
+                List<SectionUtil> items = SectionUtil.getSections(item);
+                boolean chonghe = SectionUtil.isChonghe(records, items);
+                if (chonghe) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    public static void main(String[] args) {
+        List<ReqRespResearchProductQuestionnaireItem> all = new ArrayList<>();
+        ReqRespResearchProductQuestionnaireItem re1 = new ReqRespResearchProductQuestionnaireItem("110","120", (byte) 7);
+        ReqRespResearchProductQuestionnaireItem re2 = new ReqRespResearchProductQuestionnaireItem("90","112", (byte) 7);
+        ReqRespResearchProductQuestionnaireItem re3 = new ReqRespResearchProductQuestionnaireItem("80","89", (byte) 7);
+        ReqRespResearchProductQuestionnaireItem re4 = new ReqRespResearchProductQuestionnaireItem("60","79", (byte) 7);
+        ReqRespResearchProductQuestionnaireItem re5 = new ReqRespResearchProductQuestionnaireItem("0","59", (byte) 7);
+        all.add(re1);
+        all.add(re2);
+        all.add(re3);
+        all.add(re4);
+        all.add(re5);
+        System.out.println(compareSection(all));
+    }
+}
+
+

+ 7 - 7
src/main/java/com/template/common/result/Code.java

@@ -1,7 +1,7 @@
-package com.template.common.result;
-
-public interface Code {
-    Integer getStatus();
-    Boolean getSuccess();
-    String getMsg();
-}
+package com.template.common.result;
+
+public interface Code {
+    Integer getStatus();
+    Boolean getSuccess();
+    String getMsg();
+}

+ 83 - 83
src/main/java/com/template/common/result/ResponseStatusEnum.java

@@ -1,83 +1,83 @@
-package com.template.common.result;
-
-/**
- * 响应结果枚举,用于提供给GraceJSONResult返回给前端的
- * 本枚举类中包含了很多的不同的状态码供使用,可以自定义
- * 便于更优雅的对状态码进行管理,一目了然
- */
-public enum ResponseStatusEnum implements Code{
-
-
-    SUCCESS(200, true, "操作成功!"),
-    NO_PERMISSION(401,false,"没有权限"),
-    MISSING_REQUEST_HEADER(499,false,"缺少请求头"),
-    FAILED(500, false, "操作失败!"),
-    SEND_PARAMS(501,false,"传入参数数据结构错误"),
-    SEND_PARAMS_TYPE(502,false,"传入参数数据类型错误"),
-    UN_SERVICES_ERROR(505,false,"操作失败,请联系管理员"),
-
-    // 自定义系统级别异常 54x
-    SYSTEM_ERROR(540, false, "系统错误,错误未知!"),
-    SYSTEM_INDEX_OUT_OF_BOUNDS(541, false, "系统错误,数组越界!"),
-    SYSTEM_ARITHMETIC_BY_ZERO(542, false, "系统错误,无法除零!"),
-    SYSTEM_NULL_POINTER(543, false, "系统错误,空指针!"),
-    SYSTEM_NUMBER_FORMAT(544, false, "系统错误,数字转换异常!"),
-    SYSTEM_PARSE(545, false, "系统错误,解析异常!"),
-    SYSTEM_IO(546, false, "系统错误,IO输入输出异常!"),
-    SYSTEM_FILE_NOT_FOUND(547, false, "系统错误,文件未找到!"),
-    SYSTEM_CLASS_CAST(548, false, "系统错误,类型强制转换错误!"),
-    SYSTEM_PARSER_ERROR(549, false, "系统错误,解析出错!"),
-    SYSTEM_DATE_PARSER_ERROR(550, false, "系统错误,日期解析出错!"),
-    SYSTEM_ERROR_GLOBAL(551, false, "系统繁忙,请稍后再试!"),
-    SYSTEM_ERROR_ZUUL(552, false, "请求系统过于繁忙,请稍后再试!"),
-    SYSTEM_REQUEST_METHOD_ERROR(553, false, "请求类型错误"),
-    SYSTEM_MYSQL_TIMEOUT_ERROR(554, false, "Mysql连接超时"),
-    SYSTEM_MONGO_TIMEOUT_ERROR(555, false, "Mongo连接超时"),
-    SYSTEM_PHONE_ERROR(556,false,"手机号格式错误"),
-    SYSTEM_SEND_PHONE_ERROR(557,false,"发送验证码失败"),
-    SYSTEM_TOKEN_ERROR(558,false,"token为空"),
-    SYSTEM_LOGIN_ERROR(559,false,"无效token"),
-    PARAM_ERROR(560, false, "参数不能为空!"),
-    GZH_ERROR(561, false, "设置失败,请先关联公众号!"),
-    EXISTS(999,false,"已存在");
-
-    // 响应业务状态
-    private Integer status;
-    // 调用是否成功
-    private Boolean success;
-    // 响应消息,可以为成功或者失败的消息
-    private String msg;
-
-    ResponseStatusEnum(Integer status, Boolean success, String msg) {
-        this.status = status;
-        this.success = success;
-        this.msg = msg;
-    }
-
-    public Integer status() {
-        return status;
-    }
-    public Boolean success() {
-        return success;
-    }
-    public String msg() {
-        return msg;
-    }
-
-    @Override
-    public Integer getStatus() {
-        return status;
-    }
-
-    @Override
-    public Boolean getSuccess() {
-        return success;
-    }
-
-    @Override
-    public String getMsg() {
-        return msg;
-    }
-
-
-}
+package com.template.common.result;
+
+/**
+ * 响应结果枚举,用于提供给GraceJSONResult返回给前端的
+ * 本枚举类中包含了很多的不同的状态码供使用,可以自定义
+ * 便于更优雅的对状态码进行管理,一目了然
+ */
+public enum ResponseStatusEnum implements Code{
+
+
+    SUCCESS(200, true, "操作成功!"),
+    NO_PERMISSION(401,false,"没有权限"),
+    MISSING_REQUEST_HEADER(499,false,"缺少请求头"),
+    FAILED(500, false, "操作失败!"),
+    SEND_PARAMS(501,false,"传入参数数据结构错误"),
+    SEND_PARAMS_TYPE(502,false,"传入参数数据类型错误"),
+    UN_SERVICES_ERROR(505,false,"操作失败,请联系管理员"),
+
+    // 自定义系统级别异常 54x
+    SYSTEM_ERROR(540, false, "系统错误,错误未知!"),
+    SYSTEM_INDEX_OUT_OF_BOUNDS(541, false, "系统错误,数组越界!"),
+    SYSTEM_ARITHMETIC_BY_ZERO(542, false, "系统错误,无法除零!"),
+    SYSTEM_NULL_POINTER(543, false, "系统错误,空指针!"),
+    SYSTEM_NUMBER_FORMAT(544, false, "系统错误,数字转换异常!"),
+    SYSTEM_PARSE(545, false, "系统错误,解析异常!"),
+    SYSTEM_IO(546, false, "系统错误,IO输入输出异常!"),
+    SYSTEM_FILE_NOT_FOUND(547, false, "系统错误,文件未找到!"),
+    SYSTEM_CLASS_CAST(548, false, "系统错误,类型强制转换错误!"),
+    SYSTEM_PARSER_ERROR(549, false, "系统错误,解析出错!"),
+    SYSTEM_DATE_PARSER_ERROR(550, false, "系统错误,日期解析出错!"),
+    SYSTEM_ERROR_GLOBAL(551, false, "系统繁忙,请稍后再试!"),
+    SYSTEM_ERROR_ZUUL(552, false, "请求系统过于繁忙,请稍后再试!"),
+    SYSTEM_REQUEST_METHOD_ERROR(553, false, "请求类型错误"),
+    SYSTEM_MYSQL_TIMEOUT_ERROR(554, false, "Mysql连接超时"),
+    SYSTEM_MONGO_TIMEOUT_ERROR(555, false, "Mongo连接超时"),
+    SYSTEM_PHONE_ERROR(556,false,"手机号格式错误"),
+    SYSTEM_SEND_PHONE_ERROR(557,false,"发送验证码失败"),
+    SYSTEM_TOKEN_ERROR(558,false,"token为空"),
+    SYSTEM_LOGIN_ERROR(559,false,"无效token"),
+    PARAM_ERROR(560, false, "参数不能为空!"),
+    GZH_ERROR(561, false, "设置失败,请先关联公众号!"),
+    EXISTS(999,false,"已存在");
+
+    // 响应业务状态
+    private Integer status;
+    // 调用是否成功
+    private Boolean success;
+    // 响应消息,可以为成功或者失败的消息
+    private String msg;
+
+    ResponseStatusEnum(Integer status, Boolean success, String msg) {
+        this.status = status;
+        this.success = success;
+        this.msg = msg;
+    }
+
+    public Integer status() {
+        return status;
+    }
+    public Boolean success() {
+        return success;
+    }
+    public String msg() {
+        return msg;
+    }
+
+    @Override
+    public Integer getStatus() {
+        return status;
+    }
+
+    @Override
+    public Boolean getSuccess() {
+        return success;
+    }
+
+    @Override
+    public String getMsg() {
+        return msg;
+    }
+
+
+}

+ 23 - 23
src/main/java/com/template/common/utils/AccessToken.java

@@ -1,23 +1,23 @@
-package com.template.common.utils;
-
-public class AccessToken {
-	private String access_token;// 网页获取用户信息凭证
-	private String expires_in;// 有效时间
-
-	public String getAccess_token() {
-		return access_token;
-	}
-
-	public void setAccess_token(String access_token) {
-		this.access_token = access_token;
-	}
-
-	public String getExpires_in() {
-		return expires_in;
-	}
-
-	public void setExpires_in(String expires_in) {
-		this.expires_in = expires_in;
-	}
-
-}
+package com.template.common.utils;
+
+public class AccessToken {
+	private String access_token;// 网页获取用户信息凭证
+	private String expires_in;// 有效时间
+
+	public String getAccess_token() {
+		return access_token;
+	}
+
+	public void setAccess_token(String access_token) {
+		this.access_token = access_token;
+	}
+
+	public String getExpires_in() {
+		return expires_in;
+	}
+
+	public void setExpires_in(String expires_in) {
+		this.expires_in = expires_in;
+	}
+
+}

+ 84 - 84
src/main/java/com/template/common/utils/AesTestOne.java

@@ -1,84 +1,84 @@
-package com.template.common.utils;
-
-import org.apache.commons.codec.binary.Base64;
-
-import javax.annotation.Resource;
-import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-
-/**
- * @Author: binguo
- * @Date: 2024/1/5 星期五 14:26
- * @Description: com.template.common.utils
- * @Version: 1.0
- */
-public class AesTestOne {
-
-    /**
-     * AES 对称加密(RSA非对称加密)
-     * CBC 有向量 (ECB 无向量)
-     * PKCS5Padding 填充模式(NoPadding 无填充)
-     */
-    private static final String ALG_AES_CBC_PKCS5 = "AES/CBC/PKCS5Padding";
-
-    private static final String ALGORITHM = "AES";
-
-    private static final Charset UTF8 = StandardCharsets.UTF_8;
-
-    //private static String aesKey = "61afd794ed3244e995c5e894e5788193";  // 指定好的秘钥,非Base64和16进制
-
-    private static String aesIv = "activevector4api";   // 偏移量
-
-    private static SecretKeySpec skeySpec;
-
-    private static IvParameterSpec iv;
-
-    /**
-     * 解密方法
-     * @param cipherStr Base64编码的加密字符串
-     * @return 解密后的字符串(UTF8编码)
-     * @throws Exception 异常
-     */
-    public static String decrypt(String cipherStr, String appSecret) throws Exception{
-        // step 1 获得一个密码器
-        Cipher cipher = Cipher.getInstance(ALG_AES_CBC_PKCS5);
-        // step 2 初始化密码器,指定是加密还是解密(Cipher.DECRYPT_MODE 解密; Cipher.ENCRYPT_MODE 加密)
-        // 加密时使用的盐来够造秘钥对象
-        skeySpec = new SecretKeySpec(appSecret.getBytes(),ALGORITHM);
-        // 加密时使用的向量,16位字符串
-        iv = new IvParameterSpec(aesIv.getBytes());
-        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
-        // 对加密报文进行base64解码
-        byte[] encrypted1 = Base64.decodeBase64(cipherStr);
-        // 解密后的报文数组
-        byte[] original = cipher.doFinal(encrypted1);
-        // 输出utf8编码的字符串,输出字符串需要指定编码格式
-        return new String(original, UTF8);
-    }
-
-    /**
-     * 加密
-     * @param plainText 明文
-     * @return Base64编码的密文
-     * @throws Exception  加密异常
-     */
-    public static String encrypt(String plainText, String appSecret) throws Exception{
-        Cipher cipher = Cipher.getInstance(ALG_AES_CBC_PKCS5);
-        skeySpec = new SecretKeySpec(appSecret.getBytes(),ALGORITHM);
-        iv = new IvParameterSpec(aesIv.getBytes());
-        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,iv);
-        // 这里的编码格式需要与解密编码一致
-        byte [] encryptText = cipher.doFinal(plainText.getBytes(UTF8));
-        return Base64.encodeBase64String(encryptText);
-    }
-
-    public static void main(String[] args) throws Exception {
-        // URL解码
-        System.out.println("");
-    }
-}
+package com.template.common.utils;
+
+import org.apache.commons.codec.binary.Base64;
+
+import javax.annotation.Resource;
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * @Author: binguo
+ * @Date: 2024/1/5 星期五 14:26
+ * @Description: com.template.common.utils
+ * @Version: 1.0
+ */
+public class AesTestOne {
+
+    /**
+     * AES 对称加密(RSA非对称加密)
+     * CBC 有向量 (ECB 无向量)
+     * PKCS5Padding 填充模式(NoPadding 无填充)
+     */
+    private static final String ALG_AES_CBC_PKCS5 = "AES/CBC/PKCS5Padding";
+
+    private static final String ALGORITHM = "AES";
+
+    private static final Charset UTF8 = StandardCharsets.UTF_8;
+
+    //private static String aesKey = "61afd794ed3244e995c5e894e5788193";  // 指定好的秘钥,非Base64和16进制
+
+    private static String aesIv = "activevector4api";   // 偏移量
+
+    private static SecretKeySpec skeySpec;
+
+    private static IvParameterSpec iv;
+
+    /**
+     * 解密方法
+     * @param cipherStr Base64编码的加密字符串
+     * @return 解密后的字符串(UTF8编码)
+     * @throws Exception 异常
+     */
+    public static String decrypt(String cipherStr, String appSecret) throws Exception{
+        // step 1 获得一个密码器
+        Cipher cipher = Cipher.getInstance(ALG_AES_CBC_PKCS5);
+        // step 2 初始化密码器,指定是加密还是解密(Cipher.DECRYPT_MODE 解密; Cipher.ENCRYPT_MODE 加密)
+        // 加密时使用的盐来够造秘钥对象
+        skeySpec = new SecretKeySpec(appSecret.getBytes(),ALGORITHM);
+        // 加密时使用的向量,16位字符串
+        iv = new IvParameterSpec(aesIv.getBytes());
+        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
+        // 对加密报文进行base64解码
+        byte[] encrypted1 = Base64.decodeBase64(cipherStr);
+        // 解密后的报文数组
+        byte[] original = cipher.doFinal(encrypted1);
+        // 输出utf8编码的字符串,输出字符串需要指定编码格式
+        return new String(original, UTF8);
+    }
+
+    /**
+     * 加密
+     * @param plainText 明文
+     * @return Base64编码的密文
+     * @throws Exception  加密异常
+     */
+    public static String encrypt(String plainText, String appSecret) throws Exception{
+        Cipher cipher = Cipher.getInstance(ALG_AES_CBC_PKCS5);
+        skeySpec = new SecretKeySpec(appSecret.getBytes(),ALGORITHM);
+        iv = new IvParameterSpec(aesIv.getBytes());
+        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,iv);
+        // 这里的编码格式需要与解密编码一致
+        byte [] encryptText = cipher.doFinal(plainText.getBytes(UTF8));
+        return Base64.encodeBase64String(encryptText);
+    }
+
+    public static void main(String[] args) throws Exception {
+        // URL解码
+        System.out.println("");
+    }
+}

+ 165 - 165
src/main/java/com/template/common/utils/AesUtil.java

@@ -1,165 +1,165 @@
-package com.template.common.utils;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.util.UUID;
-
-/**
- * <p>Title: AesUtil</p>
- * <p>Description: AES加密解密</p>
- * @author fengyong
- * @date 2018年9月7日
- */
-public class AesUtil {
-
-	/**
-	 * 秘钥
-	 */
-	public static final String PASSWORD_SECRET_KEY = "EasyRailEveryday";
-	
-	/**
-	 * 初始向量
-	 */
-	public static final String INITIAL_VECTOR = "EasyRailEasyRail";
-	
-    /**
-     * 加密
-     * @param content 需要加密的内容
-     * @param password  加密密码
-     * @param keySize 密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
-     * @return
-     */
-    public static byte[] encrypt(String content, String password, int keySize){
-    	try {                              
-        	//密钥长度不够用0补齐。
-    		SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(Base64Util.DEFAULT_CHARSET), keySize), "AES");
-    		//定义加密算法AES、算法模式ECB、补码方式PKCS5Padding
-            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
-    		//定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
-            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
-            //CBC模式模式下初始向量 不足16位用0补齐
-            IvParameterSpec iv = new IvParameterSpec(ZeroPadding(INITIAL_VECTOR.getBytes(Base64Util.DEFAULT_CHARSET),16));
-            byte[] byteContent = content.getBytes();  
-            //初始化加密
-            //ECB
-            //cipher.init(Cipher.ENCRYPT_MODE, key);
-            //CBC 
-			cipher.init(Cipher.ENCRYPT_MODE, key,iv);
-            byte[] result = cipher.doFinal(byteContent);
-            return result; 
-        } catch (NoSuchAlgorithmException e) {
-            e.printStackTrace();
-        } catch (NoSuchPaddingException e) {
-            e.printStackTrace();
-        } catch (InvalidKeyException e) {
-            e.printStackTrace();
-        } catch (IllegalBlockSizeException e) {
-            e.printStackTrace();
-        } catch (BadPaddingException e) {
-            e.printStackTrace();
-        } catch (InvalidAlgorithmParameterException e) {
-        	e.printStackTrace();
-        } catch (Exception e) {
-        	e.printStackTrace();
-        }
-        return null;
-    }
-    
-    /**解密
-     * @param content  待解密内容
-     * @param password 解密密钥
-     * @param keySize 密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
-     * @return
-     */
-    public static String decrypt(byte[] content, String password, int keySize) {
-        try { 
-        	//密钥长度不够用0补齐。
-    		SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(), keySize), "AES");
-    		//定义加密算法AES、算法模式ECB、补码方式PKCS5Padding
-            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
-    		//定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
-            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
-            //CBC模式模式下初始向量 不足16位用0补齐
-            IvParameterSpec iv = new IvParameterSpec(ZeroPadding(INITIAL_VECTOR.getBytes(Base64Util.DEFAULT_CHARSET),16));
-            // 初始化解密
-            //ECB
-            //cipher.init(Cipher.DECRYPT_MODE, key);
-            //CBC
-            cipher.init(Cipher.DECRYPT_MODE, key,iv);
-            byte[] result = cipher.doFinal(content);
-            return new String(result,Base64Util.DEFAULT_CHARSET); 
-        } catch (NoSuchAlgorithmException e) {
-        	e.printStackTrace();
-        } catch (NoSuchPaddingException e) {
-        	e.printStackTrace();
-        } catch (InvalidKeyException e) {
-        	e.printStackTrace();
-        } catch (IllegalBlockSizeException e) {
-        	e.printStackTrace();
-        } catch (BadPaddingException e) {
-        	e.printStackTrace();
-        } catch (InvalidAlgorithmParameterException e){
-        	e.printStackTrace();
-        } catch (Exception e){
-        	e.printStackTrace();
-        }
-        return null;
-    }
-    
-    /**将二进制转换成16进制
-     * @param buf
-     * @return
-     */
-    public static String parseByte2HexStr(byte buf[]) {
-        StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < buf.length; i++) {
-            String hex = Integer.toHexString(buf[i] & 0xFF);
-            if (hex.length() == 1) {
-                    hex = '0' + hex;
-            }
-            sb.append(hex.toUpperCase());
-        }
-        return sb.toString();
-    }
-    
-    /**将16进制转换为二进制
-     * @param hexStr
-     * @return
-     */
-    public static byte[] parseHexStr2Byte(String hexStr) {
-        if (hexStr.length() < 1){
-        	return null;
-        }
-        byte[] result = new byte[hexStr.length()/2];
-        for (int i = 0;i< hexStr.length()/2; i++) {
-            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
-            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
-            result[i] = (byte) (high * 16 + low);
-        }
-        return result;
-    }
-    
-    /**
-     * 字符达不到指定长度补0
-     * @param in 字符数组
-     * @param blockSize 长度
-     * @return
-     */
-    public static byte[] ZeroPadding(byte[] in,Integer blockSize){
-    	Integer copyLen = in.length;
-    	if (copyLen > blockSize) {
-			copyLen = blockSize;
-		}
-    	byte[] out = new byte[blockSize];
-    	System.arraycopy(in, 0, out, 0, copyLen);
-    	return out;
-    }
-
-}
+package com.template.common.utils;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.UUID;
+
+/**
+ * <p>Title: AesUtil</p>
+ * <p>Description: AES加密解密</p>
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+public class AesUtil {
+
+	/**
+	 * 秘钥
+	 */
+	public static final String PASSWORD_SECRET_KEY = "EasyRailEveryday";
+	
+	/**
+	 * 初始向量
+	 */
+	public static final String INITIAL_VECTOR = "EasyRailEasyRail";
+	
+    /**
+     * 加密
+     * @param content 需要加密的内容
+     * @param password  加密密码
+     * @param keySize 密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
+     * @return
+     */
+    public static byte[] encrypt(String content, String password, int keySize){
+    	try {                              
+        	//密钥长度不够用0补齐。
+    		SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(Base64Util.DEFAULT_CHARSET), keySize), "AES");
+    		//定义加密算法AES、算法模式ECB、补码方式PKCS5Padding
+            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
+    		//定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
+            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            //CBC模式模式下初始向量 不足16位用0补齐
+            IvParameterSpec iv = new IvParameterSpec(ZeroPadding(INITIAL_VECTOR.getBytes(Base64Util.DEFAULT_CHARSET),16));
+            byte[] byteContent = content.getBytes();  
+            //初始化加密
+            //ECB
+            //cipher.init(Cipher.ENCRYPT_MODE, key);
+            //CBC 
+			cipher.init(Cipher.ENCRYPT_MODE, key,iv);
+            byte[] result = cipher.doFinal(byteContent);
+            return result; 
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (NoSuchPaddingException e) {
+            e.printStackTrace();
+        } catch (InvalidKeyException e) {
+            e.printStackTrace();
+        } catch (IllegalBlockSizeException e) {
+            e.printStackTrace();
+        } catch (BadPaddingException e) {
+            e.printStackTrace();
+        } catch (InvalidAlgorithmParameterException e) {
+        	e.printStackTrace();
+        } catch (Exception e) {
+        	e.printStackTrace();
+        }
+        return null;
+    }
+    
+    /**解密
+     * @param content  待解密内容
+     * @param password 解密密钥
+     * @param keySize 密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
+     * @return
+     */
+    public static String decrypt(byte[] content, String password, int keySize) {
+        try { 
+        	//密钥长度不够用0补齐。
+    		SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(), keySize), "AES");
+    		//定义加密算法AES、算法模式ECB、补码方式PKCS5Padding
+            //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
+    		//定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
+            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            //CBC模式模式下初始向量 不足16位用0补齐
+            IvParameterSpec iv = new IvParameterSpec(ZeroPadding(INITIAL_VECTOR.getBytes(Base64Util.DEFAULT_CHARSET),16));
+            // 初始化解密
+            //ECB
+            //cipher.init(Cipher.DECRYPT_MODE, key);
+            //CBC
+            cipher.init(Cipher.DECRYPT_MODE, key,iv);
+            byte[] result = cipher.doFinal(content);
+            return new String(result,Base64Util.DEFAULT_CHARSET); 
+        } catch (NoSuchAlgorithmException e) {
+        	e.printStackTrace();
+        } catch (NoSuchPaddingException e) {
+        	e.printStackTrace();
+        } catch (InvalidKeyException e) {
+        	e.printStackTrace();
+        } catch (IllegalBlockSizeException e) {
+        	e.printStackTrace();
+        } catch (BadPaddingException e) {
+        	e.printStackTrace();
+        } catch (InvalidAlgorithmParameterException e){
+        	e.printStackTrace();
+        } catch (Exception e){
+        	e.printStackTrace();
+        }
+        return null;
+    }
+    
+    /**将二进制转换成16进制
+     * @param buf
+     * @return
+     */
+    public static String parseByte2HexStr(byte buf[]) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < buf.length; i++) {
+            String hex = Integer.toHexString(buf[i] & 0xFF);
+            if (hex.length() == 1) {
+                    hex = '0' + hex;
+            }
+            sb.append(hex.toUpperCase());
+        }
+        return sb.toString();
+    }
+    
+    /**将16进制转换为二进制
+     * @param hexStr
+     * @return
+     */
+    public static byte[] parseHexStr2Byte(String hexStr) {
+        if (hexStr.length() < 1){
+        	return null;
+        }
+        byte[] result = new byte[hexStr.length()/2];
+        for (int i = 0;i< hexStr.length()/2; i++) {
+            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
+            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
+            result[i] = (byte) (high * 16 + low);
+        }
+        return result;
+    }
+    
+    /**
+     * 字符达不到指定长度补0
+     * @param in 字符数组
+     * @param blockSize 长度
+     * @return
+     */
+    public static byte[] ZeroPadding(byte[] in,Integer blockSize){
+    	Integer copyLen = in.length;
+    	if (copyLen > blockSize) {
+			copyLen = blockSize;
+		}
+    	byte[] out = new byte[blockSize];
+    	System.arraycopy(in, 0, out, 0, copyLen);
+    	return out;
+    }
+
+}

+ 199 - 199
src/main/java/com/template/common/utils/AesUtils.java

@@ -1,199 +1,199 @@
-package com.template.common.utils;
-
-import lombok.extern.slf4j.Slf4j;
-import org.bouncycastle.util.encoders.Base64;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.SecretKeySpec;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * @Author: liujun
- * @Description: Aes 加解密算法
- * @Date Create in 上午 9:38$ 2017/12/26 0026$
- * @Modify By:
- */
-@Slf4j
-public class AesUtils {
-    private static String password = "52D04DC20036DBD8";
-    /**
-     * @Author liujun
-     * @Description:
-     * @params: * @param content 需要加密的内容
-     * @param password  加密密码
-     * @Date 上午 9:41 2017/12/26 0026
-     */
-    public static String encrypt(String content) {
-
-        if(password.length()<16) {
-            password = password + "0000000000000000".substring(0, 16-password.length());
-        }
-        else if(password.length()>16) {
-            password = password.substring(0, 16);
-        }
-
-        return bytes2HexString(encryptAES(content.getBytes(), password.getBytes()));
-    }
-
-
-    /**
-     * @Author liujun
-     * @Description:
-     * @params: * @param content 待解密内容
-     * @param password 解密密钥
-     * @Date 上午 9:40 2017/12/26 0026
-     */
-    public static String decrypt(String content) {
-        if(password.length()<16) {
-            password = password + "0000000000000000".substring(0, 16-password.length());
-        }
-        else if(password.length()>16) {
-            password = password.substring(0, 16);
-        }
-
-        return new String(decryptAES(hexString2Bytes(content), password.getBytes()));
-    }
-
-    /**
-     * AES 加密
-     *
-     * @param data 明文
-     * @param key  16、24、32 字节秘钥
-     * @return 密文
-     */
-    public static byte[] encryptAES(final byte[] data, final byte[] key) {
-
-        try {
-            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
-            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
-            byte[] byteContent = data;
-            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
-            byte[] result = cipher.doFinal(byteContent);
-            return result; // 加密
-        } catch (NoSuchAlgorithmException e) {
-            log.error(e.getMessage(),e);
-        } catch (NoSuchPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (InvalidKeyException e) {
-            log.error(e.getMessage(),e);
-        } catch (IllegalBlockSizeException e) {
-            log.error(e.getMessage(),e);
-        } catch (BadPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (Exception e) {
-            log.error(e.getMessage(),e);
-        }
-        return null;
-    }
-
-    /**
-     * AES 解密
-     *
-     * @param data 密文
-     * @param key  16、24、32 字节秘钥
-     * @return 明文
-     */
-    public static byte[] decryptAES(final byte[] data, final byte[] key) {
-
-        try {
-            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
-            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
-            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
-            byte[] result = cipher.doFinal(data);
-            return result; // 加密
-        } catch (NoSuchAlgorithmException e) {
-            log.error(e.getMessage(),e);
-        } catch (NoSuchPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (InvalidKeyException e) {
-            log.error(e.getMessage(),e);
-        } catch (IllegalBlockSizeException e) {
-            log.error(e.getMessage(),e);
-        } catch (BadPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (Exception e) {
-            log.error(e.getMessage(),e);
-        }
-        return null;
-    }
-
-    public static String bytes2HexString(final byte[] bytes) {
-        if (bytes == null) return null;
-        int len = bytes.length;
-        if (len <= 0) return null;
-        char[] ret = new char[len << 1];
-        for (int i = 0, j = 0; i < len; i++) {
-            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
-            ret[j++] = hexDigits[bytes[i] & 0x0f];
-        }
-        return new String(ret);
-    }
-
-    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
-
-    public static byte[] hexString2Bytes(String hexString) {
-        if (isSpace(hexString)) return null;
-        int len = hexString.length();
-        if (len % 2 != 0) {
-            hexString = "0" + hexString;
-            len = len + 1;
-        }
-        char[] hexBytes = hexString.toUpperCase().toCharArray();
-        byte[] ret = new byte[len >> 1];
-        for (int i = 0; i < len; i += 2) {
-            ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
-        }
-        return ret;
-    }
-
-    private static int hex2Dec(final char hexChar) {
-        if (hexChar >= '0' && hexChar <= '9') {
-            return hexChar - '0';
-        } else if (hexChar >= 'A' && hexChar <= 'F') {
-            return hexChar - 'A' + 10;
-        } else {
-            throw new IllegalArgumentException();
-        }
-    }
-
-    public static byte[] base64Encode(final byte[] input) {
-        return Base64.encode(input);
-    }
-
-    public static byte[] base64Decode(final byte[] input) {
-
-        return Base64.decode(input);
-    }
-
-    private static boolean isSpace(final String s) {
-        if (s == null) return true;
-        for (int i = 0, len = s.length(); i < len; ++i) {
-            if (!Character.isWhitespace(s.charAt(i))) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    public static void main(String[] args) {
-        String s="{\n" +
-                "  \"categoryId\": \"72cf28a8789643bbbbb62d08ee91f17e\",\n" +
-                "     \"luid\": \"80A036D93CFB\",\n" +
-                "     \"type\":\"4\",\n" +
-                "     \"userName\":\"13097286670\",\n" +
-                "     \"startTime\":\"1682389484000\",\n" +
-                "     \"endTime\":\"1684981484000\",\n" +
-                "     \"password\":\"A08E87B5E777EBEE2C6EF3262F069D5A\"\n" +
-                "}";
-        //加密
-        String encryptString = AesUtils.encrypt("548903");
-        System.out.println("加密后字符串:"+encryptString);
-        //解密
-        String decryptString = AesUtils.decrypt(encryptString);
-        System.out.println("解密后字符串:"+decryptString);
-    }
-}
+package com.template.common.utils;
+
+import lombok.extern.slf4j.Slf4j;
+import org.bouncycastle.util.encoders.Base64;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * @Author: liujun
+ * @Description: Aes 加解密算法
+ * @Date Create in 上午 9:38$ 2017/12/26 0026$
+ * @Modify By:
+ */
+@Slf4j
+public class AesUtils {
+    private static String password = "52D04DC20036DBD8";
+    /**
+     * @Author liujun
+     * @Description:
+     * @params: * @param content 需要加密的内容
+     * @param password  加密密码
+     * @Date 上午 9:41 2017/12/26 0026
+     */
+    public static String encrypt(String content) {
+
+        if(password.length()<16) {
+            password = password + "0000000000000000".substring(0, 16-password.length());
+        }
+        else if(password.length()>16) {
+            password = password.substring(0, 16);
+        }
+
+        return bytes2HexString(encryptAES(content.getBytes(), password.getBytes()));
+    }
+
+
+    /**
+     * @Author liujun
+     * @Description:
+     * @params: * @param content 待解密内容
+     * @param password 解密密钥
+     * @Date 上午 9:40 2017/12/26 0026
+     */
+    public static String decrypt(String content) {
+        if(password.length()<16) {
+            password = password + "0000000000000000".substring(0, 16-password.length());
+        }
+        else if(password.length()>16) {
+            password = password.substring(0, 16);
+        }
+
+        return new String(decryptAES(hexString2Bytes(content), password.getBytes()));
+    }
+
+    /**
+     * AES 加密
+     *
+     * @param data 明文
+     * @param key  16、24、32 字节秘钥
+     * @return 密文
+     */
+    public static byte[] encryptAES(final byte[] data, final byte[] key) {
+
+        try {
+            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
+            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
+            byte[] byteContent = data;
+            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
+            byte[] result = cipher.doFinal(byteContent);
+            return result; // 加密
+        } catch (NoSuchAlgorithmException e) {
+            log.error(e.getMessage(),e);
+        } catch (NoSuchPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (InvalidKeyException e) {
+            log.error(e.getMessage(),e);
+        } catch (IllegalBlockSizeException e) {
+            log.error(e.getMessage(),e);
+        } catch (BadPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (Exception e) {
+            log.error(e.getMessage(),e);
+        }
+        return null;
+    }
+
+    /**
+     * AES 解密
+     *
+     * @param data 密文
+     * @param key  16、24、32 字节秘钥
+     * @return 明文
+     */
+    public static byte[] decryptAES(final byte[] data, final byte[] key) {
+
+        try {
+            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
+            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
+            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
+            byte[] result = cipher.doFinal(data);
+            return result; // 加密
+        } catch (NoSuchAlgorithmException e) {
+            log.error(e.getMessage(),e);
+        } catch (NoSuchPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (InvalidKeyException e) {
+            log.error(e.getMessage(),e);
+        } catch (IllegalBlockSizeException e) {
+            log.error(e.getMessage(),e);
+        } catch (BadPaddingException e) {
+            log.error(e.getMessage(),e);
+        } catch (Exception e) {
+            log.error(e.getMessage(),e);
+        }
+        return null;
+    }
+
+    public static String bytes2HexString(final byte[] bytes) {
+        if (bytes == null) return null;
+        int len = bytes.length;
+        if (len <= 0) return null;
+        char[] ret = new char[len << 1];
+        for (int i = 0, j = 0; i < len; i++) {
+            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
+            ret[j++] = hexDigits[bytes[i] & 0x0f];
+        }
+        return new String(ret);
+    }
+
+    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+    public static byte[] hexString2Bytes(String hexString) {
+        if (isSpace(hexString)) return null;
+        int len = hexString.length();
+        if (len % 2 != 0) {
+            hexString = "0" + hexString;
+            len = len + 1;
+        }
+        char[] hexBytes = hexString.toUpperCase().toCharArray();
+        byte[] ret = new byte[len >> 1];
+        for (int i = 0; i < len; i += 2) {
+            ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
+        }
+        return ret;
+    }
+
+    private static int hex2Dec(final char hexChar) {
+        if (hexChar >= '0' && hexChar <= '9') {
+            return hexChar - '0';
+        } else if (hexChar >= 'A' && hexChar <= 'F') {
+            return hexChar - 'A' + 10;
+        } else {
+            throw new IllegalArgumentException();
+        }
+    }
+
+    public static byte[] base64Encode(final byte[] input) {
+        return Base64.encode(input);
+    }
+
+    public static byte[] base64Decode(final byte[] input) {
+
+        return Base64.decode(input);
+    }
+
+    private static boolean isSpace(final String s) {
+        if (s == null) return true;
+        for (int i = 0, len = s.length(); i < len; ++i) {
+            if (!Character.isWhitespace(s.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public static void main(String[] args) {
+        String s="{\n" +
+                "  \"categoryId\": \"72cf28a8789643bbbbb62d08ee91f17e\",\n" +
+                "     \"luid\": \"80A036D93CFB\",\n" +
+                "     \"type\":\"4\",\n" +
+                "     \"userName\":\"13097286670\",\n" +
+                "     \"startTime\":\"1682389484000\",\n" +
+                "     \"endTime\":\"1684981484000\",\n" +
+                "     \"password\":\"A08E87B5E777EBEE2C6EF3262F069D5A\"\n" +
+                "}";
+        //加密
+        String encryptString = AesUtils.encrypt("548903");
+        System.out.println("加密后字符串:"+encryptString);
+        //解密
+        String decryptString = AesUtils.decrypt(encryptString);
+        System.out.println("解密后字符串:"+decryptString);
+    }
+}

+ 47 - 47
src/main/java/com/template/common/utils/Base64Util.java

@@ -1,47 +1,47 @@
-package com.template.common.utils;
-
-import org.apache.tomcat.util.codec.binary.Base64;
-
-import java.nio.charset.Charset;
-
-/**
- * <p>Title: Base64Util</p>
- * <p>Description: Base64Util工具类 --- 加密和解密</p>
- * @author fengyong
- * @date 2018年9月7日
- */
-public class Base64Util {
-	
-	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
-	/**
-     * 解密
-     * @param str
-     * @return
-     */
-    public static String decodeStr(String str){
-        if (str == null) {
-			return null;
-		}
-		if (str.length() == 0) {
-			return "";
-		}
-		return new String(Base64.decodeBase64(new String(str).getBytes(DEFAULT_CHARSET)),DEFAULT_CHARSET).trim();
-    }
-
-    /**
-     * 加密
-     * 
-     * @param str
-     * @return
-     */
-    public static String encodeStr(String str){
-        if (str == null) {
-			return null;
-		}
-		if (str.length() == 0) {
-			return "";
-		}
-        return new String(Base64.encodeBase64Chunked(str.getBytes(DEFAULT_CHARSET)),DEFAULT_CHARSET).trim();
-    }
-
-}
+package com.template.common.utils;
+
+import org.apache.tomcat.util.codec.binary.Base64;
+
+import java.nio.charset.Charset;
+
+/**
+ * <p>Title: Base64Util</p>
+ * <p>Description: Base64Util工具类 --- 加密和解密</p>
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+public class Base64Util {
+	
+	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
+	/**
+     * 解密
+     * @param str
+     * @return
+     */
+    public static String decodeStr(String str){
+        if (str == null) {
+			return null;
+		}
+		if (str.length() == 0) {
+			return "";
+		}
+		return new String(Base64.decodeBase64(new String(str).getBytes(DEFAULT_CHARSET)),DEFAULT_CHARSET).trim();
+    }
+
+    /**
+     * 加密
+     * 
+     * @param str
+     * @return
+     */
+    public static String encodeStr(String str){
+        if (str == null) {
+			return null;
+		}
+		if (str.length() == 0) {
+			return "";
+		}
+        return new String(Base64.encodeBase64Chunked(str.getBytes(DEFAULT_CHARSET)),DEFAULT_CHARSET).trim();
+    }
+
+}

+ 211 - 211
src/main/java/com/template/common/utils/CommonUtil.java

@@ -1,211 +1,211 @@
-package com.template.common.utils;
-
-import lombok.extern.slf4j.Slf4j;
-
-import javax.servlet.http.HttpServletRequest;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.MessageDigest;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * 公共工具类
- **/
-@Slf4j
-public class CommonUtil {
-    /**
-     * 检查字符串是否符合正则表达式
-     */
-    public static boolean checkStrByRegx(String regex, String str) {
-        //使用Pattern类的compile()方法编译正则表达式
-        Pattern pattern = Pattern.compile(regex);
-        //使用Matcher类的matcher()方法将正则表达式和字符串进行匹配
-        Matcher matcher = pattern.matcher(str);
-        //返回匹配结果
-        return matcher.matches();
-    }
-
-    /**
-     * 检测客户端参数
-     *
-     * @param code   状态码
-     * @param object 对象
-     * @return 返回类型
-     */
-    public static Map<String, Object> getReturnMap(String code, Object object) {
-        Map<String, Object> returnMap = new HashMap<>();
-        returnMap.put("code", code);
-        returnMap.put("msg", object);
-        return returnMap;
-    }
-
-    public static String getNumberFromString(String string) {
-        Pattern pattern = Pattern.compile("\\d+");
-        Matcher matcher = pattern.matcher(string);
-        if (matcher.find()) {
-            return matcher.group();
-        }
-        return null;
-    }
-
-    /**
-     * 获取ip
-     *
-     * @param request
-     * @return
-     */
-    public static String getIpAddr(HttpServletRequest request) {
-        String ipAddress = null;
-        try {
-            ipAddress = request.getHeader("x-forwarded-for");
-            System.out.println("x-forwarded-for=" + ipAddress);
-            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
-                ipAddress = request.getHeader("Proxy-Client-IP");
-                System.out.println("Proxy-Client-IP=" + ipAddress);
-            }
-            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
-                ipAddress = request.getHeader("WL-Proxy-Client-IP");
-                System.out.println("WL-Proxy-Client-IP=" + ipAddress);
-            }
-            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
-                ipAddress = request.getRemoteAddr();
-                System.out.println("getRemoteAddr=" + ipAddress);
-                if (ipAddress.equals("127.0.0.1")) {
-                    // 根据网卡取本机配置的IP
-                    InetAddress inet = null;
-                    try {
-                        inet = InetAddress.getLocalHost();
-                    } catch (UnknownHostException e) {
-                        e.printStackTrace();
-                    }
-                    ipAddress = inet.getHostAddress();
-                    System.out.println("getHostAddress=" + ipAddress);
-                }
-            }
-            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
-            if (ipAddress != null && ipAddress.length() > 15) {
-                // "***.***.***.***".length()
-                // = 15
-                if (ipAddress.indexOf(",") > 0) {
-                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
-                }
-            }
-        } catch (Exception e) {
-            ipAddress = "";
-        }
-        return ipAddress;
-    }
-
-
-    /**
-     * 获取全部请求头
-     *
-     * @param request
-     * @return
-     */
-    public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
-        Enumeration<String> headerNames = request.getHeaderNames();
-        Map<String, String> map = new HashMap<>();
-        while (headerNames.hasMoreElements()) {
-            String key = headerNames.nextElement();
-            //根据名称获取请求头的值
-            String value = request.getHeader(key);
-            map.put(key, value);
-        }
-
-        return map;
-    }
-
-
-    /**
-     * MD5加密
-     *
-     * @param data
-     * @return
-     */
-    public static String MD5(String data) {
-        try {
-            MessageDigest md = MessageDigest.getInstance("MD5");
-            byte[] array = md.digest(data.getBytes("UTF-8"));
-            StringBuilder sb = new StringBuilder();
-            for (byte item : array) {
-                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
-            }
-
-            return sb.toString().toUpperCase();
-        } catch (Exception exception) {
-        }
-        return null;
-    }
-
-
-    /**
-     * 获取验证码随机数
-     *
-     * @param length
-     * @return
-     */
-    public static String getRandomCode(int length) {
-        String sources = "0123456789";
-        Random random = new Random();
-        StringBuilder sb = new StringBuilder();
-        for (int j = 0; j < length; j++) {
-            sb.append(sources.charAt(random.nextInt(9)));
-        }
-        return sb.toString();
-    }
-
-    /**
-     * 获取当前时间戳
-     *
-     * @return
-     */
-    public static long getCurrentTimestamp() {
-        return System.currentTimeMillis();
-    }
-
-    /**
-     * 生成uuid
-     *
-     * @return
-     */
-    public static String generateUUID() {
-        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
-    }
-
-    /**
-     * 获取随机长度的串
-     *
-     * @param length
-     * @return
-     */
-    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
-
-    public static String getStringNumRandom(int length) {
-        //生成随机数字和字母,
-        Random random = new Random();
-        StringBuilder saltString = new StringBuilder(length);
-        for (int i = 1; i <= length; ++i) {
-            saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
-        }
-        return saltString.toString();
-    }
-
-    /**
-     * LocalDate 拼接时间转成 LocalDateTime
-     *
-     * @param localDate
-     * @param timeStr   HH:mm:ss
-     * @return
-     */
-    public static LocalDateTime localDateToTime(LocalDate localDate, String timeStr) {
-        LocalTime time = LocalTime.parse(timeStr);
-        return LocalDateTime.of(localDate.getYear(), localDate.getMonth(), localDate.getDayOfMonth(),
-                time.getHour(), time.getMinute(), time.getSecond());
-    }
-}
+package com.template.common.utils;
+
+import lombok.extern.slf4j.Slf4j;
+
+import javax.servlet.http.HttpServletRequest;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.MessageDigest;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 公共工具类
+ **/
+@Slf4j
+public class CommonUtil {
+    /**
+     * 检查字符串是否符合正则表达式
+     */
+    public static boolean checkStrByRegx(String regex, String str) {
+        //使用Pattern类的compile()方法编译正则表达式
+        Pattern pattern = Pattern.compile(regex);
+        //使用Matcher类的matcher()方法将正则表达式和字符串进行匹配
+        Matcher matcher = pattern.matcher(str);
+        //返回匹配结果
+        return matcher.matches();
+    }
+
+    /**
+     * 检测客户端参数
+     *
+     * @param code   状态码
+     * @param object 对象
+     * @return 返回类型
+     */
+    public static Map<String, Object> getReturnMap(String code, Object object) {
+        Map<String, Object> returnMap = new HashMap<>();
+        returnMap.put("code", code);
+        returnMap.put("msg", object);
+        return returnMap;
+    }
+
+    public static String getNumberFromString(String string) {
+        Pattern pattern = Pattern.compile("\\d+");
+        Matcher matcher = pattern.matcher(string);
+        if (matcher.find()) {
+            return matcher.group();
+        }
+        return null;
+    }
+
+    /**
+     * 获取ip
+     *
+     * @param request
+     * @return
+     */
+    public static String getIpAddr(HttpServletRequest request) {
+        String ipAddress = null;
+        try {
+            ipAddress = request.getHeader("x-forwarded-for");
+            System.out.println("x-forwarded-for=" + ipAddress);
+            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
+                ipAddress = request.getHeader("Proxy-Client-IP");
+                System.out.println("Proxy-Client-IP=" + ipAddress);
+            }
+            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
+                ipAddress = request.getHeader("WL-Proxy-Client-IP");
+                System.out.println("WL-Proxy-Client-IP=" + ipAddress);
+            }
+            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
+                ipAddress = request.getRemoteAddr();
+                System.out.println("getRemoteAddr=" + ipAddress);
+                if (ipAddress.equals("127.0.0.1")) {
+                    // 根据网卡取本机配置的IP
+                    InetAddress inet = null;
+                    try {
+                        inet = InetAddress.getLocalHost();
+                    } catch (UnknownHostException e) {
+                        e.printStackTrace();
+                    }
+                    ipAddress = inet.getHostAddress();
+                    System.out.println("getHostAddress=" + ipAddress);
+                }
+            }
+            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
+            if (ipAddress != null && ipAddress.length() > 15) {
+                // "***.***.***.***".length()
+                // = 15
+                if (ipAddress.indexOf(",") > 0) {
+                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
+                }
+            }
+        } catch (Exception e) {
+            ipAddress = "";
+        }
+        return ipAddress;
+    }
+
+
+    /**
+     * 获取全部请求头
+     *
+     * @param request
+     * @return
+     */
+    public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
+        Enumeration<String> headerNames = request.getHeaderNames();
+        Map<String, String> map = new HashMap<>();
+        while (headerNames.hasMoreElements()) {
+            String key = headerNames.nextElement();
+            //根据名称获取请求头的值
+            String value = request.getHeader(key);
+            map.put(key, value);
+        }
+
+        return map;
+    }
+
+
+    /**
+     * MD5加密
+     *
+     * @param data
+     * @return
+     */
+    public static String MD5(String data) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            byte[] array = md.digest(data.getBytes("UTF-8"));
+            StringBuilder sb = new StringBuilder();
+            for (byte item : array) {
+                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
+            }
+
+            return sb.toString().toUpperCase();
+        } catch (Exception exception) {
+        }
+        return null;
+    }
+
+
+    /**
+     * 获取验证码随机数
+     *
+     * @param length
+     * @return
+     */
+    public static String getRandomCode(int length) {
+        String sources = "0123456789";
+        Random random = new Random();
+        StringBuilder sb = new StringBuilder();
+        for (int j = 0; j < length; j++) {
+            sb.append(sources.charAt(random.nextInt(9)));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 获取当前时间戳
+     *
+     * @return
+     */
+    public static long getCurrentTimestamp() {
+        return System.currentTimeMillis();
+    }
+
+    /**
+     * 生成uuid
+     *
+     * @return
+     */
+    public static String generateUUID() {
+        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
+    }
+
+    /**
+     * 获取随机长度的串
+     *
+     * @param length
+     * @return
+     */
+    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+
+    public static String getStringNumRandom(int length) {
+        //生成随机数字和字母,
+        Random random = new Random();
+        StringBuilder saltString = new StringBuilder(length);
+        for (int i = 1; i <= length; ++i) {
+            saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
+        }
+        return saltString.toString();
+    }
+
+    /**
+     * LocalDate 拼接时间转成 LocalDateTime
+     *
+     * @param localDate
+     * @param timeStr   HH:mm:ss
+     * @return
+     */
+    public static LocalDateTime localDateToTime(LocalDate localDate, String timeStr) {
+        LocalTime time = LocalTime.parse(timeStr);
+        return LocalDateTime.of(localDate.getYear(), localDate.getMonth(), localDate.getDayOfMonth(),
+                time.getHour(), time.getMinute(), time.getSecond());
+    }
+}

+ 9 - 9
src/main/java/com/template/common/utils/DataBliu.java

@@ -1,9 +1,9 @@
-package com.template.common.utils;
-
-public class DataBliu {
-
-    public static double getTwo(double d1){
-        return (double) Math.round(d1 * 100) / 100;
-    }
-
-}
+package com.template.common.utils;
+
+public class DataBliu {
+
+    public static double getTwo(double d1){
+        return (double) Math.round(d1 * 100) / 100;
+    }
+
+}

+ 241 - 241
src/main/java/com/template/common/utils/DateUtils.java

@@ -1,241 +1,241 @@
-package com.template.common.utils;
-
-import org.springframework.stereotype.Component;
-
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-
-/**
- * <p>Title: DateUtils</p>
- * <p>Description:日期工具类 </p>
- * 
- * @author fengyong
- * @date 2018年9月7日
- */
-@Component // 加此注解是把此类实例化spring容器中
-public class DateUtils {
-
-	/**
-	 * 默认日期格式
-	 */
-	public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
-
-	/**
-	 * 如2018 0901 232211(年月日时分秒)
-	 * 
-	 * @return
-	 */
-	public String yyyyMMddHHmmss() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如20180901
-	 * 
-	 * @return
-	 */
-	public static String getYYYYMMdd() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如180901
-	 * @return
-	 */
-	public String getYYMMdd() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如201809
-	 * @return
-	 */
-	public String getYYYYMM() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如 2018/02/11
-	 * @return
-	 */
-	public String getQueryEndDate() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如 2018/02/11
-	 * @return
-	 */
-	public String getQueryStartDate() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-		Calendar cal = Calendar.getInstance();
-		cal.add(Calendar.DAY_OF_YEAR, -30);
-		return sdf.format(cal.getTime());
-	}
-
-	/**
-	 * 如 2018/02/11 12:30:00
-	 * @return
-	 */
-	public static String getQueryEndTime() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-		return sdf.format(Calendar.getInstance().getTime());
-	}
-
-	/**
-	 * 如 2018/02/11
-	 * @return
-	 */
-	public String getQueryStartTime() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-		Calendar cal = Calendar.getInstance();
-		cal.add(Calendar.DAY_OF_YEAR, -30);
-		return sdf.format(cal.getTime());
-	}
-
-	public String getQueryTwoAgoDate() {
-		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
-		Calendar cal = Calendar.getInstance();
-		cal.add(Calendar.DAY_OF_YEAR, -2);
-		return sdf.format(cal.getTime());
-	}
-
-	/**
-	 * 字符串转换成日期
-	 * 
-	 * @param str 字符串
-	 * @param format 日期格式
-	 * @return 日期
-	 */
-	public static Date str2Date(String str, String format) {
-		if (null == str || "".equals(str)) {
-			return null;
-		}
-		// 如果没有指定字符串转换的格式,则用默认格式进行转换
-		if (null == format || "".equals(format)) {
-			format = DEFAULT_FORMAT;
-		}
-		SimpleDateFormat sdf = new SimpleDateFormat(format);
-		Date date = null;
-		try {
-			date = sdf.parse(str);
-			return date;
-		} catch (ParseException e) {
-		}
-		return null;
-	}
-
-	/**
-	 * @param date 日期
-	 * @param format 日期格式
-	 * @return 字符串
-	 */
-	public static String date2Str(Date date, String format) {
-		if (null == date) {
-			return null;
-		}
-		SimpleDateFormat sdf = new SimpleDateFormat(format);
-		return sdf.format(date);
-	}
-
-	/**
-	 * 时间戳转换为字符串
-	 * @param time
-	 * @return
-	 */
-	public static String timestamp2Str(Timestamp time) {
-		Date date = new Date(time.getTime());
-		return date2Str(date, DEFAULT_FORMAT);
-	}
-
-	/**
-	 * 字符串转换为时间
-	 * @param str
-	 * @return
-	 */
-	public static Timestamp str2Timestamp(String str) {
-		Date date = str2Date(str, DEFAULT_FORMAT);
-		return new Timestamp(date.getTime());
-	}
-
-	/**
-	 * 字符串转换为时间
-	 * @param str
-	 * @return
-	 */
-	public static Timestamp str2Timestamp(String str, String formatStr) {
-		if (null == str) {
-			return null;
-		}
-		Date date = str2Date(str, formatStr);
-		return new Timestamp(date.getTime());
-	}
-
-	/**
-	 * 获取某年第一天日期
-	 * @param year 年份
-	 * @return Date
-	 */
-	public static Date getYearFirst(int year) {
-		Calendar calendar = Calendar.getInstance();
-		calendar.clear();
-		calendar.set(Calendar.YEAR, year);
-		Date currYearFirst = calendar.getTime();
-		return currYearFirst;
-	}
-
-	/**
-	 * 获取某年最后一天日期
-	 * @param year  年份
-	 * @return Date
-	 */
-	public static Date getYearLast(int year) {
-		Calendar calendar = Calendar.getInstance();
-		calendar.clear();
-		calendar.set(Calendar.YEAR, year);
-		calendar.roll(Calendar.DAY_OF_YEAR, -1);
-		Date currYearLast = calendar.getTime();
-
-		return currYearLast;
-	}
-
-	@SuppressWarnings("static-access")
-	public static Date getnextLast(String datetime, int year) {
-		Calendar calendar = new GregorianCalendar();
-		Date date = null;
-		if (datetime.length() > 7) {
-			date = str2Date(datetime, "yyyy-MM-dd");
-		} else {
-			date = str2Date(datetime, "yyyy-MM");
-		}
-		calendar.setTime(date);
-		calendar.add(calendar.YEAR, year);// 把日期往后增加一年.整数往后推,负数往前移动
-		date = calendar.getTime();
-		return date;
-
-	}
-
-	public static String getrightDate(String datetime, int year) {
-		String date = "";
-		String years = datetime.substring(0, 4);
-		String dates = datetime.substring(4, datetime.length());
-		Integer s = new Integer(years) + year;
-		date = s + dates;
-		return date;
-	}
-
-	public static void main(String[] args) {
-		System.out.println(getrightDate("2018-09", 4));
-		System.out.println(date2Str(getnextLast("2018-09", 4), "yyyy-MM"));
-	}
-
-}
+package com.template.common.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+/**
+ * <p>Title: DateUtils</p>
+ * <p>Description:日期工具类 </p>
+ * 
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+@Component // 加此注解是把此类实例化spring容器中
+public class DateUtils {
+
+	/**
+	 * 默认日期格式
+	 */
+	public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
+
+	/**
+	 * 如2018 0901 232211(年月日时分秒)
+	 * 
+	 * @return
+	 */
+	public String yyyyMMddHHmmss() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如20180901
+	 * 
+	 * @return
+	 */
+	public static String getYYYYMMdd() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如180901
+	 * @return
+	 */
+	public String getYYMMdd() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如201809
+	 * @return
+	 */
+	public String getYYYYMM() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如 2018/02/11
+	 * @return
+	 */
+	public String getQueryEndDate() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如 2018/02/11
+	 * @return
+	 */
+	public String getQueryStartDate() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+		Calendar cal = Calendar.getInstance();
+		cal.add(Calendar.DAY_OF_YEAR, -30);
+		return sdf.format(cal.getTime());
+	}
+
+	/**
+	 * 如 2018/02/11 12:30:00
+	 * @return
+	 */
+	public static String getQueryEndTime() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+		return sdf.format(Calendar.getInstance().getTime());
+	}
+
+	/**
+	 * 如 2018/02/11
+	 * @return
+	 */
+	public String getQueryStartTime() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+		Calendar cal = Calendar.getInstance();
+		cal.add(Calendar.DAY_OF_YEAR, -30);
+		return sdf.format(cal.getTime());
+	}
+
+	public String getQueryTwoAgoDate() {
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+		Calendar cal = Calendar.getInstance();
+		cal.add(Calendar.DAY_OF_YEAR, -2);
+		return sdf.format(cal.getTime());
+	}
+
+	/**
+	 * 字符串转换成日期
+	 * 
+	 * @param str 字符串
+	 * @param format 日期格式
+	 * @return 日期
+	 */
+	public static Date str2Date(String str, String format) {
+		if (null == str || "".equals(str)) {
+			return null;
+		}
+		// 如果没有指定字符串转换的格式,则用默认格式进行转换
+		if (null == format || "".equals(format)) {
+			format = DEFAULT_FORMAT;
+		}
+		SimpleDateFormat sdf = new SimpleDateFormat(format);
+		Date date = null;
+		try {
+			date = sdf.parse(str);
+			return date;
+		} catch (ParseException e) {
+		}
+		return null;
+	}
+
+	/**
+	 * @param date 日期
+	 * @param format 日期格式
+	 * @return 字符串
+	 */
+	public static String date2Str(Date date, String format) {
+		if (null == date) {
+			return null;
+		}
+		SimpleDateFormat sdf = new SimpleDateFormat(format);
+		return sdf.format(date);
+	}
+
+	/**
+	 * 时间戳转换为字符串
+	 * @param time
+	 * @return
+	 */
+	public static String timestamp2Str(Timestamp time) {
+		Date date = new Date(time.getTime());
+		return date2Str(date, DEFAULT_FORMAT);
+	}
+
+	/**
+	 * 字符串转换为时间
+	 * @param str
+	 * @return
+	 */
+	public static Timestamp str2Timestamp(String str) {
+		Date date = str2Date(str, DEFAULT_FORMAT);
+		return new Timestamp(date.getTime());
+	}
+
+	/**
+	 * 字符串转换为时间
+	 * @param str
+	 * @return
+	 */
+	public static Timestamp str2Timestamp(String str, String formatStr) {
+		if (null == str) {
+			return null;
+		}
+		Date date = str2Date(str, formatStr);
+		return new Timestamp(date.getTime());
+	}
+
+	/**
+	 * 获取某年第一天日期
+	 * @param year 年份
+	 * @return Date
+	 */
+	public static Date getYearFirst(int year) {
+		Calendar calendar = Calendar.getInstance();
+		calendar.clear();
+		calendar.set(Calendar.YEAR, year);
+		Date currYearFirst = calendar.getTime();
+		return currYearFirst;
+	}
+
+	/**
+	 * 获取某年最后一天日期
+	 * @param year  年份
+	 * @return Date
+	 */
+	public static Date getYearLast(int year) {
+		Calendar calendar = Calendar.getInstance();
+		calendar.clear();
+		calendar.set(Calendar.YEAR, year);
+		calendar.roll(Calendar.DAY_OF_YEAR, -1);
+		Date currYearLast = calendar.getTime();
+
+		return currYearLast;
+	}
+
+	@SuppressWarnings("static-access")
+	public static Date getnextLast(String datetime, int year) {
+		Calendar calendar = new GregorianCalendar();
+		Date date = null;
+		if (datetime.length() > 7) {
+			date = str2Date(datetime, "yyyy-MM-dd");
+		} else {
+			date = str2Date(datetime, "yyyy-MM");
+		}
+		calendar.setTime(date);
+		calendar.add(calendar.YEAR, year);// 把日期往后增加一年.整数往后推,负数往前移动
+		date = calendar.getTime();
+		return date;
+
+	}
+
+	public static String getrightDate(String datetime, int year) {
+		String date = "";
+		String years = datetime.substring(0, 4);
+		String dates = datetime.substring(4, datetime.length());
+		Integer s = new Integer(years) + year;
+		date = s + dates;
+		return date;
+	}
+
+	public static void main(String[] args) {
+		System.out.println(getrightDate("2018-09", 4));
+		System.out.println(date2Str(getnextLast("2018-09", 4), "yyyy-MM"));
+	}
+
+}

+ 82 - 82
src/main/java/com/template/common/utils/EncryptUtil.java

@@ -1,82 +1,82 @@
-package com.template.common.utils;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.DESKeySpec;
-import java.security.SecureRandom;
-import java.util.Base64;
-
-/**
- * 对称加密算法
- *
- * @Date: 2024/2/26 星期一 10:31
- * @Description: com.template.common.utils
- * @Version: 1.0
- */
-public class EncryptUtil {
-    public static String secretKeyB = "com.template.common.utils";
-    private final static String DES = "DES";
-
-    //加密
-    public static String encrypt(String data) {
-        byte[] bt;
-        try {
-            bt = encrypt(data.getBytes(), secretKeyB.getBytes());
-            //加密
-            String strs = Base64.getEncoder().encodeToString(bt);
-            return strs;
-        } catch (Exception e) {
-            e.printStackTrace();
-            return null;
-        }
-    }
-
-    //解密
-    public static String decrypt(String data) {
-        if (data == null) {
-            return null;
-        }
-        byte[] buf;
-        byte[] bt;
-        try {
-            //解密
-            buf = Base64.getDecoder().decode(data);
-            bt = decrypt(buf, secretKeyB.getBytes());
-            return new String(bt);
-        } catch (Exception e) {
-            e.printStackTrace();
-            return null;
-        }
-    }
-
-    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
-        // 生成可信任的随机数源
-        SecureRandom sr = new SecureRandom();
-        // 从原始密钥数据创建DESKeySpec对象
-        DESKeySpec dks = new DESKeySpec(key);
-        // 创建密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
-        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
-        SecretKey securekey = keyFactory.generateSecret(dks);
-        // Cipher对象实际完成加密操作
-        Cipher cipher = Cipher.getInstance(DES);
-        // 用密钥初始化Cipher对象
-        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
-        return cipher.doFinal(data);
-    }
-
-    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
-        // 生成可信任的随机数源
-        SecureRandom sr = new SecureRandom();
-        // 从原始密钥数据创建DESKeySpec对象
-        DESKeySpec dks = new DESKeySpec(key);
-        // 创建密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
-        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
-        SecretKey securekey = keyFactory.generateSecret(dks);
-        // Cipher对象实际完成解密操作
-        Cipher cipher = Cipher.getInstance(DES);
-        // 用密钥初始化Cipher对象
-        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
-        return cipher.doFinal(data);
-    }
-}
+package com.template.common.utils;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESKeySpec;
+import java.security.SecureRandom;
+import java.util.Base64;
+
+/**
+ * 对称加密算法
+ *
+ * @Date: 2024/2/26 星期一 10:31
+ * @Description: com.template.common.utils
+ * @Version: 1.0
+ */
+public class EncryptUtil {
+    public static String secretKeyB = "com.template.common.utils";
+    private final static String DES = "DES";
+
+    //加密
+    public static String encrypt(String data) {
+        byte[] bt;
+        try {
+            bt = encrypt(data.getBytes(), secretKeyB.getBytes());
+            //加密
+            String strs = Base64.getEncoder().encodeToString(bt);
+            return strs;
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    //解密
+    public static String decrypt(String data) {
+        if (data == null) {
+            return null;
+        }
+        byte[] buf;
+        byte[] bt;
+        try {
+            //解密
+            buf = Base64.getDecoder().decode(data);
+            bt = decrypt(buf, secretKeyB.getBytes());
+            return new String(bt);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
+        // 生成可信任的随机数源
+        SecureRandom sr = new SecureRandom();
+        // 从原始密钥数据创建DESKeySpec对象
+        DESKeySpec dks = new DESKeySpec(key);
+        // 创建密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
+        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
+        SecretKey securekey = keyFactory.generateSecret(dks);
+        // Cipher对象实际完成加密操作
+        Cipher cipher = Cipher.getInstance(DES);
+        // 用密钥初始化Cipher对象
+        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
+        return cipher.doFinal(data);
+    }
+
+    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
+        // 生成可信任的随机数源
+        SecureRandom sr = new SecureRandom();
+        // 从原始密钥数据创建DESKeySpec对象
+        DESKeySpec dks = new DESKeySpec(key);
+        // 创建密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
+        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
+        SecretKey securekey = keyFactory.generateSecret(dks);
+        // Cipher对象实际完成解密操作
+        Cipher cipher = Cipher.getInstance(DES);
+        // 用密钥初始化Cipher对象
+        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
+        return cipher.doFinal(data);
+    }
+}

+ 41 - 41
src/main/java/com/template/common/utils/EncryptionUtil.java

@@ -1,41 +1,41 @@
-package com.template.common.utils;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-public class EncryptionUtil {
-
-
-    private static final int MAX_JSON_STRING = 40;
-
-    /**
-     * 将需要加密的字段分批加密
-     *
-     * @param jsonString
-     * @param publicKey
-     * @return
-     * @throws Exception
-     */
-    public Map<Object, Object> encryption(String jsonString, String publicKey) throws Exception {
-        int length = jsonString.length();
-        int offset = 0;
-        int i = 0;
-        HashMap<Object, Object> map = new HashMap<>();
-//        判断字符串长度是否大于40,大于就截取前40位,分批加密
-        while (length - offset > 0) {
-            if (length - offset > MAX_JSON_STRING) {
-                String substring = jsonString.substring(offset, offset + MAX_JSON_STRING);
-                String encrypt = RSAUtils.encrypt(substring, RSAUtils.getPublicKey(publicKey));
-                map.put(i, encrypt);
-            } else {
-                String substring = jsonString.substring(offset,length);
-                String encrypt = RSAUtils.encrypt(substring, RSAUtils.getPublicKey(publicKey));
-                map.put(i, encrypt);
-            }
-            i++;
-            offset = i * MAX_JSON_STRING;
-        }
-        return map;
-    }
-}
+package com.template.common.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+public class EncryptionUtil {
+
+
+    private static final int MAX_JSON_STRING = 40;
+
+    /**
+     * 将需要加密的字段分批加密
+     *
+     * @param jsonString
+     * @param publicKey
+     * @return
+     * @throws Exception
+     */
+    public Map<Object, Object> encryption(String jsonString, String publicKey) throws Exception {
+        int length = jsonString.length();
+        int offset = 0;
+        int i = 0;
+        HashMap<Object, Object> map = new HashMap<>();
+//        判断字符串长度是否大于40,大于就截取前40位,分批加密
+        while (length - offset > 0) {
+            if (length - offset > MAX_JSON_STRING) {
+                String substring = jsonString.substring(offset, offset + MAX_JSON_STRING);
+                String encrypt = RSAUtils.encrypt(substring, RSAUtils.getPublicKey(publicKey));
+                map.put(i, encrypt);
+            } else {
+                String substring = jsonString.substring(offset,length);
+                String encrypt = RSAUtils.encrypt(substring, RSAUtils.getPublicKey(publicKey));
+                map.put(i, encrypt);
+            }
+            i++;
+            offset = i * MAX_JSON_STRING;
+        }
+        return map;
+    }
+}

+ 74 - 74
src/main/java/com/template/common/utils/ExcelClassField.java

@@ -1,75 +1,75 @@
-package com.template.common.utils;
- 
-import java.util.LinkedHashMap;
- 
-/**
- *  */
-public class ExcelClassField {
- 
-    /** 字段名称 */
-    private String fieldName;
- 
-    /** 表头名称 */
-    private String name;
- 
-    /** 映射关系 */
-    private LinkedHashMap<String, String> kvMap;
- 
-    /** 示例值 */
-    private Object example;
- 
-    /** 排序 */
-    private int sort;
- 
-    /** 是否为注解字段:0-否,1-是 */
-    private int hasAnnotation;
- 
-    public String getFieldName() {
-        return fieldName;
-    }
- 
-    public void setFieldName(String fieldName) {
-        this.fieldName = fieldName;
-    }
- 
-    public String getName() {
-        return name;
-    }
- 
-    public void setName(String name) {
-        this.name = name;
-    }
- 
-    public LinkedHashMap<String, String> getKvMap() {
-        return kvMap;
-    }
- 
-    public void setKvMap(LinkedHashMap<String, String> kvMap) {
-        this.kvMap = kvMap;
-    }
- 
-    public Object getExample() {
-        return example;
-    }
- 
-    public void setExample(Object example) {
-        this.example = example;
-    }
- 
-    public int getSort() {
-        return sort;
-    }
- 
-    public void setSort(int sort) {
-        this.sort = sort;
-    }
- 
-    public int getHasAnnotation() {
-        return hasAnnotation;
-    }
- 
-    public void setHasAnnotation(int hasAnnotation) {
-        this.hasAnnotation = hasAnnotation;
-    }
- 
+package com.template.common.utils;
+ 
+import java.util.LinkedHashMap;
+ 
+/**
+ *  */
+public class ExcelClassField {
+ 
+    /** 字段名称 */
+    private String fieldName;
+ 
+    /** 表头名称 */
+    private String name;
+ 
+    /** 映射关系 */
+    private LinkedHashMap<String, String> kvMap;
+ 
+    /** 示例值 */
+    private Object example;
+ 
+    /** 排序 */
+    private int sort;
+ 
+    /** 是否为注解字段:0-否,1-是 */
+    private int hasAnnotation;
+ 
+    public String getFieldName() {
+        return fieldName;
+    }
+ 
+    public void setFieldName(String fieldName) {
+        this.fieldName = fieldName;
+    }
+ 
+    public String getName() {
+        return name;
+    }
+ 
+    public void setName(String name) {
+        this.name = name;
+    }
+ 
+    public LinkedHashMap<String, String> getKvMap() {
+        return kvMap;
+    }
+ 
+    public void setKvMap(LinkedHashMap<String, String> kvMap) {
+        this.kvMap = kvMap;
+    }
+ 
+    public Object getExample() {
+        return example;
+    }
+ 
+    public void setExample(Object example) {
+        this.example = example;
+    }
+ 
+    public int getSort() {
+        return sort;
+    }
+ 
+    public void setSort(int sort) {
+        this.sort = sort;
+    }
+ 
+    public int getHasAnnotation() {
+        return hasAnnotation;
+    }
+ 
+    public void setHasAnnotation(int hasAnnotation) {
+        this.hasAnnotation = hasAnnotation;
+    }
+ 
 }

+ 22 - 22
src/main/java/com/template/common/utils/ExcelUtil3.java

@@ -1,22 +1,22 @@
-package com.template.common.utils;
-
-
-
-import com.alibaba.excel.EasyExcel;
-import com.alibaba.excel.support.ExcelTypeEnum;
-
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.net.URLEncoder;
-import java.util.List;
-
-public class ExcelUtil3 {
-
-    public static void process(String fileName, List target, Class clazs , HttpServletResponse response) throws IOException {
-        response.setCharacterEncoding("UTF-8");
-        response.setContentType("application/vnd.ms-excel");
-        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
-        EasyExcel.write(response.getOutputStream(), clazs).excelType(ExcelTypeEnum.XLSX).autoCloseStream(Boolean.TRUE)
-                .sheet("预警报表").doWrite(target);
-    }
-}
+package com.template.common.utils;
+
+
+
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.support.ExcelTypeEnum;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.util.List;
+
+public class ExcelUtil3 {
+
+    public static void process(String fileName, List target, Class clazs , HttpServletResponse response) throws IOException {
+        response.setCharacterEncoding("UTF-8");
+        response.setContentType("application/vnd.ms-excel");
+        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
+        EasyExcel.write(response.getOutputStream(), clazs).excelType(ExcelTypeEnum.XLSX).autoCloseStream(Boolean.TRUE)
+                .sheet("预警报表").doWrite(target);
+    }
+}

+ 64 - 64
src/main/java/com/template/common/utils/ExcelUtils.java

@@ -1,64 +1,64 @@
-package com.template.common.utils;
-
-import lombok.extern.slf4j.Slf4j;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.springframework.boot.system.ApplicationHome;
-
-import javax.servlet.http.HttpServletResponse;
-import java.io.*;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-
-/**
- * @Author: binguo
- * @Date: 2023/7/10 星期一 14:21
- * @Description: com.repair.common.utils
- * @Version: 1.0
- */
-@Slf4j
-public class ExcelUtils {
-    public static void fileDownload(String fileName, HttpServletResponse response) {
-        try {
-            ApplicationHome applicationHome = new ApplicationHome(ExcelUtils.class);
-            String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
-            String decode = URLDecoder.decode(pathResouce, "utf-8");
-            File readPath = new File(decode + "/project/repair" + File.separator);
-            File file = new File(readPath.getAbsolutePath() + fileName);
-            // 获取文件名
-            String filename = file.getName();
-            // 获取文件后缀名
-            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
-            InputStream inputStream = new FileInputStream(file);//根据路径获取要下载的文件输入流
-            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
-            response.setCharacterEncoding("utf-8");
-            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
-            OutputStream out = response.getOutputStream();
-            byte[] b = new byte[1024];  //创建数据缓冲区
-            int length;
-            while ((length = inputStream.read(b)) > 0) {  //把文件流写到缓冲区里
-                out.write(b, 0, length);
-            }
-            out.flush();
-            out.close();
-            inputStream.close();
-        } catch (IOException ex) {
-            System.out.println("模板导出失败:" + ex.getMessage());
-            ex.printStackTrace();
-        }
-    }
-
-    public static void excelDownload(Workbook workbook, String fileName, HttpServletResponse response) {
-        try {
-            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
-            response.setCharacterEncoding("utf-8");
-            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
-            OutputStream out = response.getOutputStream();
-            workbook.write(out);
-            out.flush();
-            out.close();
-        } catch (IOException ex) {
-            System.out.println("模板导出失败:" + ex.getMessage());
-            ex.printStackTrace();
-        }
-    }
-}
+package com.template.common.utils;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.springframework.boot.system.ApplicationHome;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/7/10 星期一 14:21
+ * @Description: com.repair.common.utils
+ * @Version: 1.0
+ */
+@Slf4j
+public class ExcelUtils {
+    public static void fileDownload(String fileName, HttpServletResponse response) {
+        try {
+            ApplicationHome applicationHome = new ApplicationHome(ExcelUtils.class);
+            String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
+            String decode = URLDecoder.decode(pathResouce, "utf-8");
+            File readPath = new File(decode + "/project/repair" + File.separator);
+            File file = new File(readPath.getAbsolutePath() + fileName);
+            // 获取文件名
+            String filename = file.getName();
+            // 获取文件后缀名
+            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
+            InputStream inputStream = new FileInputStream(file);//根据路径获取要下载的文件输入流
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setCharacterEncoding("utf-8");
+            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
+            OutputStream out = response.getOutputStream();
+            byte[] b = new byte[1024];  //创建数据缓冲区
+            int length;
+            while ((length = inputStream.read(b)) > 0) {  //把文件流写到缓冲区里
+                out.write(b, 0, length);
+            }
+            out.flush();
+            out.close();
+            inputStream.close();
+        } catch (IOException ex) {
+            System.out.println("模板导出失败:" + ex.getMessage());
+            ex.printStackTrace();
+        }
+    }
+
+    public static void excelDownload(Workbook workbook, String fileName, HttpServletResponse response) {
+        try {
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setCharacterEncoding("utf-8");
+            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
+            OutputStream out = response.getOutputStream();
+            workbook.write(out);
+            out.flush();
+            out.close();
+        } catch (IOException ex) {
+            System.out.println("模板导出失败:" + ex.getMessage());
+            ex.printStackTrace();
+        }
+    }
+}

File diff suppressed because it is too large
+ 1007 - 1007
src/main/java/com/template/common/utils/ExcelUtils2.java


+ 76 - 76
src/main/java/com/template/common/utils/FileUtils.java

@@ -1,76 +1,76 @@
-package com.template.common.utils;
-
-
-import org.apache.commons.fileupload.FileItem;
-import org.apache.commons.fileupload.FileItemFactory;
-import org.apache.commons.fileupload.disk.DiskFileItemFactory;
-import org.springframework.http.MediaType;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.multipart.commons.CommonsMultipartFile;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @Author: binguo
- * @Date: 2023/12/27 星期三 11:08
- * @Description: com.template.common.utils
- * @Version: 1.0
- */
-public class FileUtils {
-
-
-    /**
-     * 获取封装得MultipartFile
-     *
-     * @param inputStream inputStream
-     * @return MultipartFile
-     */
-    public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
-        FileItem fileItem = createFileItem(inputStream, fileName);
-        //CommonsMultipartFile是feign对multipartFile的封装,但是要FileItem类对象
-        return new CommonsMultipartFile(fileItem);
-    }
-    /**
-     * FileItem类对象创建
-     *
-     * @param inputStream inputStream
-     * @param fileName    fileName
-     * @return FileItem
-     */
-    public static FileItem createFileItem(InputStream inputStream, String fileName) {
-        FileItemFactory factory = new DiskFileItemFactory(16, null);
-        String textFieldName = "file";
-        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
-        int bytesRead = 0;
-        byte[] buffer = new byte[10 * 1024 * 1024];
-        OutputStream os = null;
-        //使用输出流输出输入流的字节
-        try {
-            os = item.getOutputStream();
-            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
-                os.write(buffer, 0, bytesRead);
-            }
-            inputStream.close();
-        } catch (IOException e) {
-            throw new IllegalArgumentException("文件上传失败");
-        } finally {
-            if (os != null) {
-                try {
-                    os.close();
-                } catch (IOException e) {
-
-                }
-            }
-            if (inputStream != null) {
-                try {
-                    inputStream.close();
-                } catch (IOException e) {
-                }
-            }
-        }
-
-        return item;
-    }
-}
+package com.template.common.utils;
+
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileItemFactory;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.springframework.http.MediaType;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/12/27 星期三 11:08
+ * @Description: com.template.common.utils
+ * @Version: 1.0
+ */
+public class FileUtils {
+
+
+    /**
+     * 获取封装得MultipartFile
+     *
+     * @param inputStream inputStream
+     * @return MultipartFile
+     */
+    public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
+        FileItem fileItem = createFileItem(inputStream, fileName);
+        //CommonsMultipartFile是feign对multipartFile的封装,但是要FileItem类对象
+        return new CommonsMultipartFile(fileItem);
+    }
+    /**
+     * FileItem类对象创建
+     *
+     * @param inputStream inputStream
+     * @param fileName    fileName
+     * @return FileItem
+     */
+    public static FileItem createFileItem(InputStream inputStream, String fileName) {
+        FileItemFactory factory = new DiskFileItemFactory(16, null);
+        String textFieldName = "file";
+        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
+        int bytesRead = 0;
+        byte[] buffer = new byte[10 * 1024 * 1024];
+        OutputStream os = null;
+        //使用输出流输出输入流的字节
+        try {
+            os = item.getOutputStream();
+            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
+                os.write(buffer, 0, bytesRead);
+            }
+            inputStream.close();
+        } catch (IOException e) {
+            throw new IllegalArgumentException("文件上传失败");
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException e) {
+
+                }
+            }
+            if (inputStream != null) {
+                try {
+                    inputStream.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+
+        return item;
+    }
+}

+ 18 - 18
src/main/java/com/template/common/utils/GetVertifyCode.java

@@ -1,18 +1,18 @@
-package com.template.common.utils;
-
-import java.util.Random;
-
-public class GetVertifyCode {
-
-    public static String getRandomNumCode(int number){
-        String codeNum = "";
-        int [] numbers = {0,1,2,3,4,5,6,7,8,9};
-        Random random = new Random();
-        for (int i = 0; i < number; i++) {
-            int next = random.nextInt(10000);
-            codeNum+=numbers[next%10];
-        }
-        return codeNum;
-    }
-
-}
+package com.template.common.utils;
+
+import java.util.Random;
+
+public class GetVertifyCode {
+
+    public static String getRandomNumCode(int number){
+        String codeNum = "";
+        int [] numbers = {0,1,2,3,4,5,6,7,8,9};
+        Random random = new Random();
+        for (int i = 0; i < number; i++) {
+            int next = random.nextInt(10000);
+            codeNum+=numbers[next%10];
+        }
+        return codeNum;
+    }
+
+}

+ 241 - 241
src/main/java/com/template/common/utils/HttpClientUtils.java

@@ -1,241 +1,241 @@
-package com.template.common.utils;
-
-import org.apache.http.HttpEntity;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.conn.ssl.DefaultHostnameVerifier;
-import org.apache.http.conn.util.PublicSuffixMatcher;
-import org.apache.http.conn.util.PublicSuffixMatcherLoader;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.util.EntityUtils;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>Title: HttpClientUtils</p>
- * <p>Description: httpClient 工具类</p>
- * @author fengyong
- * @date 2018年9月7日
- */
-public class HttpClientUtils {
-	
-	/**
-	 * 默认参数设置
-	 * setConnectTimeout:设置连接超时时间,单位毫秒。
-	 * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
-	 * setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
-	 */
-	private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
-	
-	/**
-	 * 静态内部类---作用:单例产生类的实例
-	 * @author Administrator
-	 *
-	 */
-	private static class LazyHolder {    
-       private static final HttpClientUtils INSTANCE = new HttpClientUtils();    
-       
-    }  
-	private HttpClientUtils(){}
-	public static HttpClientUtils getInstance(){
-		return LazyHolder.INSTANCE;    
-	}
-	
-	/**
-	 * 发送 post请求
-	 * @param httpUrl 地址
-	 */
-	public String sendHttpPost(String httpUrl) {
-		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
-		return sendHttpPost(httpPost);
-	}
-	
-	/**
-	 * 发送 post请求
-	 * @param httpUrl 地址
-	 * @param params 参数(格式:key1=value1&key2=value2)
-	 */
-	public String sendHttpPost(String httpUrl, String params) {
-		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
-		try {
-			//设置参数
-			StringEntity stringEntity = new StringEntity(params, "UTF-8");
-			stringEntity.setContentType("application/x-www-form-urlencoded");
-			httpPost.setEntity(stringEntity);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return sendHttpPost(httpPost);
-	}
-	
-	/**
-	 * 发送 post请求
-	 * @param httpUrl 地址
-	 * @param maps 参数
-	 */
-	public String sendHttpPost(String httpUrl, Map<String, String> maps) {
-		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
-		// 创建参数队列  
-		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
-		for (String key : maps.keySet()) {
-			nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
-		}
-		try {
-			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return sendHttpPost(httpPost);
-	}
-	
-	/**
-	 * 发送Post请求
-	 * @param httpPost
-	 * @return
-	 */
-	private String sendHttpPost(HttpPost httpPost) {
-		CloseableHttpClient httpClient = null;
-		CloseableHttpResponse response = null;
-		HttpEntity entity = null;
-		String responseContent = null;
-		try {
-			// 创建默认的httpClient实例
-			httpClient = HttpClients.createDefault();
-			httpPost.setConfig(requestConfig);
-			// 执行请求
-			long execStart = System.currentTimeMillis();
-			response = httpClient.execute(httpPost);
-			long execEnd = System.currentTimeMillis();
-			System.out.println("=================执行post请求耗时:"+(execEnd-execStart)+"ms");
-			long getStart = System.currentTimeMillis();
-			entity = response.getEntity();
-			responseContent = EntityUtils.toString(entity, "UTF-8");
-			long getEnd = System.currentTimeMillis();
-			System.out.println("=================获取响应结果耗时:"+(getEnd-getStart)+"ms");
-		} catch (Exception e) {
-			e.printStackTrace();
-		} finally {
-			try {
-				// 关闭连接,释放资源
-				if (response != null) {
-					response.close();
-				}
-				if (httpClient != null) {
-					httpClient.close();
-				}
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-		return responseContent;
-	}
-
-	/**
-	 * 发送 get请求
-	 * @param httpUrl
-	 */
-	public String sendHttpGet(String httpUrl) {
-		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
-		return sendHttpGet(httpGet);
-	}
-	
-	/**
-	 * 发送 get请求Https
-	 * @param httpUrl
-	 */
-	public String sendHttpsGet(String httpUrl) {
-		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
-		return sendHttpsGet(httpGet);
-	}
-	
-	/**
-	 * 发送Get请求
-	 * @param httpPost
-	 * @return
-	 */
-	private String sendHttpGet(HttpGet httpGet) {
-		CloseableHttpClient httpClient = null;
-		CloseableHttpResponse response = null;
-		HttpEntity entity = null;
-		String responseContent = null;
-		try {
-			// 创建默认的httpClient实例.
-
-			
-			httpClient = HttpClients.createDefault();
-
-			httpGet.setConfig(requestConfig);
-			// 执行请求
-			response = httpClient.execute(httpGet);
-			entity = response.getEntity();
-			responseContent = EntityUtils.toString(entity, "UTF-8");
-		} catch (Exception e) {
-			e.printStackTrace();
-		} finally {
-			try {
-				// 关闭连接,释放资源
-				if (response != null) {
-					response.close();
-				}
-				if (httpClient != null) {
-					httpClient.close();
-				}
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-		return responseContent;
-	}
-	
-	/**
-	 * 发送Get请求Https
-	 * @param httpPost
-	 * @return
-	 */
-	private String sendHttpsGet(HttpGet httpGet) {
-		CloseableHttpClient httpClient = null;
-		CloseableHttpResponse response = null;
-		HttpEntity entity = null;
-		String responseContent = null;
-		try {
-			// 创建默认的httpClient实例.
-			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
-			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
-			httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
-			httpGet.setConfig(requestConfig);
-			// 执行请求
-			response = httpClient.execute(httpGet);
-			entity = response.getEntity();
-			responseContent = EntityUtils.toString(entity, "UTF-8");
-		} catch (Exception e) {
-			e.printStackTrace();
-		} finally {
-			try {
-				// 关闭连接,释放资源
-				if (response != null) {
-					response.close();
-				}
-				if (httpClient != null) {
-					httpClient.close();
-				}
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-		return responseContent;
-	}
-	
-	
-	
-}
+package com.template.common.utils;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.DefaultHostnameVerifier;
+import org.apache.http.conn.util.PublicSuffixMatcher;
+import org.apache.http.conn.util.PublicSuffixMatcherLoader;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>Title: HttpClientUtils</p>
+ * <p>Description: httpClient 工具类</p>
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+public class HttpClientUtils {
+	
+	/**
+	 * 默认参数设置
+	 * setConnectTimeout:设置连接超时时间,单位毫秒。
+	 * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
+	 * setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
+	 */
+	private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
+	
+	/**
+	 * 静态内部类---作用:单例产生类的实例
+	 * @author Administrator
+	 *
+	 */
+	private static class LazyHolder {    
+       private static final HttpClientUtils INSTANCE = new HttpClientUtils();    
+       
+    }  
+	private HttpClientUtils(){}
+	public static HttpClientUtils getInstance(){
+		return LazyHolder.INSTANCE;    
+	}
+	
+	/**
+	 * 发送 post请求
+	 * @param httpUrl 地址
+	 */
+	public String sendHttpPost(String httpUrl) {
+		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
+		return sendHttpPost(httpPost);
+	}
+	
+	/**
+	 * 发送 post请求
+	 * @param httpUrl 地址
+	 * @param params 参数(格式:key1=value1&key2=value2)
+	 */
+	public String sendHttpPost(String httpUrl, String params) {
+		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
+		try {
+			//设置参数
+			StringEntity stringEntity = new StringEntity(params, "UTF-8");
+			stringEntity.setContentType("application/x-www-form-urlencoded");
+			httpPost.setEntity(stringEntity);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return sendHttpPost(httpPost);
+	}
+	
+	/**
+	 * 发送 post请求
+	 * @param httpUrl 地址
+	 * @param maps 参数
+	 */
+	public String sendHttpPost(String httpUrl, Map<String, String> maps) {
+		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost  
+		// 创建参数队列  
+		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
+		for (String key : maps.keySet()) {
+			nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
+		}
+		try {
+			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return sendHttpPost(httpPost);
+	}
+	
+	/**
+	 * 发送Post请求
+	 * @param httpPost
+	 * @return
+	 */
+	private String sendHttpPost(HttpPost httpPost) {
+		CloseableHttpClient httpClient = null;
+		CloseableHttpResponse response = null;
+		HttpEntity entity = null;
+		String responseContent = null;
+		try {
+			// 创建默认的httpClient实例
+			httpClient = HttpClients.createDefault();
+			httpPost.setConfig(requestConfig);
+			// 执行请求
+			long execStart = System.currentTimeMillis();
+			response = httpClient.execute(httpPost);
+			long execEnd = System.currentTimeMillis();
+			System.out.println("=================执行post请求耗时:"+(execEnd-execStart)+"ms");
+			long getStart = System.currentTimeMillis();
+			entity = response.getEntity();
+			responseContent = EntityUtils.toString(entity, "UTF-8");
+			long getEnd = System.currentTimeMillis();
+			System.out.println("=================获取响应结果耗时:"+(getEnd-getStart)+"ms");
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭连接,释放资源
+				if (response != null) {
+					response.close();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return responseContent;
+	}
+
+	/**
+	 * 发送 get请求
+	 * @param httpUrl
+	 */
+	public String sendHttpGet(String httpUrl) {
+		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
+		return sendHttpGet(httpGet);
+	}
+	
+	/**
+	 * 发送 get请求Https
+	 * @param httpUrl
+	 */
+	public String sendHttpsGet(String httpUrl) {
+		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
+		return sendHttpsGet(httpGet);
+	}
+	
+	/**
+	 * 发送Get请求
+	 * @param httpPost
+	 * @return
+	 */
+	private String sendHttpGet(HttpGet httpGet) {
+		CloseableHttpClient httpClient = null;
+		CloseableHttpResponse response = null;
+		HttpEntity entity = null;
+		String responseContent = null;
+		try {
+			// 创建默认的httpClient实例.
+
+			
+			httpClient = HttpClients.createDefault();
+
+			httpGet.setConfig(requestConfig);
+			// 执行请求
+			response = httpClient.execute(httpGet);
+			entity = response.getEntity();
+			responseContent = EntityUtils.toString(entity, "UTF-8");
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭连接,释放资源
+				if (response != null) {
+					response.close();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return responseContent;
+	}
+	
+	/**
+	 * 发送Get请求Https
+	 * @param httpPost
+	 * @return
+	 */
+	private String sendHttpsGet(HttpGet httpGet) {
+		CloseableHttpClient httpClient = null;
+		CloseableHttpResponse response = null;
+		HttpEntity entity = null;
+		String responseContent = null;
+		try {
+			// 创建默认的httpClient实例.
+			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
+			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
+			httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
+			httpGet.setConfig(requestConfig);
+			// 执行请求
+			response = httpClient.execute(httpGet);
+			entity = response.getEntity();
+			responseContent = EntityUtils.toString(entity, "UTF-8");
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				// 关闭连接,释放资源
+				if (response != null) {
+					response.close();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return responseContent;
+	}
+	
+	
+	
+}

+ 112 - 112
src/main/java/com/template/common/utils/HttpUtils.java

@@ -1,112 +1,112 @@
-package com.template.common.utils;
-
-import org.apache.http.HttpEntity;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.util.EntityUtils;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @Author: binguo
- * @Date: 2023/8/21 星期一 14:58
- * @Description: com.repair.common.utils
- * @Version: 1.0
- */
-public class HttpUtils {
-    /**
-     * 发送http post请求
-     *
-     * @param
-     *
-     * @param
-     *
-     */
-    public static String post(String url, Map<String, String> params){
-        CloseableHttpClient httpClient = null;
-        HttpPost httpPost = null;
-        String re = "";
-        try {
-            httpClient = HttpClients.createDefault();
-            RequestConfig requestConfig = RequestConfig.custom()
-                    .setSocketTimeout(20000).setConnectTimeout(20000).build();
-            httpPost = new HttpPost(url);
-            httpPost.setConfig(requestConfig);
-            List<NameValuePair> ps = new ArrayList<NameValuePair>();
-            for (String pKey : params.keySet()) {
-                ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
-            }
-            httpPost.setEntity(new UrlEncodedFormEntity(ps));
-            CloseableHttpResponse response = httpClient.execute(httpPost);
-            HttpEntity httpEntity = response.getEntity();
-            re = EntityUtils.toString(httpEntity, "utf-8");
-        } catch (ClientProtocolException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } finally {
-            try {
-                if (httpPost != null) {
-                    httpPost.releaseConnection();
-                }
-                if (httpClient != null) {
-                    httpClient.close();
-                }
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-        return re;
-    }
-
-    /**
-     * 发送post请求Https,参数是字符串
-     *
-     * @param
-     * @return
-     */
-    public static String post(String url, String body){
-        String str = "";
-        CloseableHttpClient httpClient = null;
-        HttpPost httpPost = null;
-        try {
-            httpClient = HttpClients.createDefault();
-            RequestConfig requestConfig = RequestConfig.custom()
-                    .setSocketTimeout(20000).setConnectTimeout(20000).build();
-            httpPost = new HttpPost(url);
-            httpPost.setConfig(requestConfig);
-            httpPost.setEntity(new StringEntity(body, "utf-8"));
-            CloseableHttpResponse response = httpClient.execute(httpPost);
-            HttpEntity httpEntity = response.getEntity();
-            str = EntityUtils.toString(httpEntity, "utf-8");
-
-        } catch (ClientProtocolException e) {
-            e.printStackTrace();
-        } catch (IOException e) {
-            e.printStackTrace();
-        } finally {
-            try {
-                if (httpPost != null) {
-                    httpPost.releaseConnection();
-                }
-                if (httpClient != null) {
-                    httpClient.close();
-                }
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-        return str;
-    }
-}
+package com.template.common.utils;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/8/21 星期一 14:58
+ * @Description: com.repair.common.utils
+ * @Version: 1.0
+ */
+public class HttpUtils {
+    /**
+     * 发送http post请求
+     *
+     * @param
+     *
+     * @param
+     *
+     */
+    public static String post(String url, Map<String, String> params){
+        CloseableHttpClient httpClient = null;
+        HttpPost httpPost = null;
+        String re = "";
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom()
+                    .setSocketTimeout(20000).setConnectTimeout(20000).build();
+            httpPost = new HttpPost(url);
+            httpPost.setConfig(requestConfig);
+            List<NameValuePair> ps = new ArrayList<NameValuePair>();
+            for (String pKey : params.keySet()) {
+                ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(ps));
+            CloseableHttpResponse response = httpClient.execute(httpPost);
+            HttpEntity httpEntity = response.getEntity();
+            re = EntityUtils.toString(httpEntity, "utf-8");
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (httpPost != null) {
+                    httpPost.releaseConnection();
+                }
+                if (httpClient != null) {
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return re;
+    }
+
+    /**
+     * 发送post请求Https,参数是字符串
+     *
+     * @param
+     * @return
+     */
+    public static String post(String url, String body){
+        String str = "";
+        CloseableHttpClient httpClient = null;
+        HttpPost httpPost = null;
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom()
+                    .setSocketTimeout(20000).setConnectTimeout(20000).build();
+            httpPost = new HttpPost(url);
+            httpPost.setConfig(requestConfig);
+            httpPost.setEntity(new StringEntity(body, "utf-8"));
+            CloseableHttpResponse response = httpClient.execute(httpPost);
+            HttpEntity httpEntity = response.getEntity();
+            str = EntityUtils.toString(httpEntity, "utf-8");
+
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (httpPost != null) {
+                    httpPost.releaseConnection();
+                }
+                if (httpClient != null) {
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return str;
+    }
+}

File diff suppressed because it is too large
+ 530 - 530
src/main/java/com/template/common/utils/HttpsClient.java


+ 105 - 105
src/main/java/com/template/common/utils/JWTUtil.java

@@ -1,105 +1,105 @@
-package com.template.common.utils;
-
-
-import com.auth0.jwt.JWT;
-import com.auth0.jwt.JWTVerifier;
-import com.auth0.jwt.algorithms.Algorithm;
-import com.auth0.jwt.interfaces.Claim;
-import com.auth0.jwt.interfaces.DecodedJWT;
-import com.template.model.pojo.RepairAdmin;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * jwt 工具
- **/
-@Slf4j
-public class JWTUtil {
-
-    private static String SIGNATURE = "token!@#$%^7890";
-
-    /**
-     * token过期时间,7天
-     */
-//    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;
-    private static final long EXPIRED = 1000 * 60 * 60 * 24;
-
-    /**
-     * 生成token 有过期时间
-     * @return 返回token
-     */
-    public static String getToken(RepairAdmin ra){
-
-        // 签发时间
-        Date iatDate = new Date();
-
-//        // 过期时间
-//        Calendar nowTime = Calendar.getInstance();
-//        nowTime.add(Calendar.DAY_OF_WEEK, 3);
-//        Date expiresDate = nowTime.getTime();
-
-        Map<String, Object> map = new HashMap<>();
-        map.put("alg", "HMAC256");
-        map.put("typ", "JWT");
-        String token = JWT.create()
-                .withHeader(map) // header
-                .withClaim("account", ra.getAccount()) // 账号
-                .withClaim("password", ra.getPassword()) // 密码
-                .withExpiresAt(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED)) // 设置过期时间。过期时间要大于签发时间
-                .withIssuedAt(iatDate) // 设置签发时间
-                .sign(Algorithm.HMAC256(SIGNATURE)); // 加密
-        return token;
-
-//
-//        JWTCreator.Builder builder = JWT.create();
-//        map.forEach((k,v)->{
-//            builder.withClaim(k,v);
-//        });
-//        Calendar instance = Calendar.getInstance();
-//        instance.add(Calendar.SECOND,7);
-//        builder.withExpiresAt(instance.getTime());
-//        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
-    }
-
-    public static long getExpired() {
-        return EXPIRED;
-    }
-
-
-    /**
-     * 验证token
-     * @param token
-     */
-    public static void verify(String token){
-        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
-    }
-
-    /**
-     * 获取token中payload
-     * @param token
-     * @return
-     */
-    public static DecodedJWT getToken(String token){
-        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
-    }
-
-
-
-    /*
-     * 解密Token
-     * */
-    public static Map<String, Claim> verifyToken(String token)  {
-        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
-        DecodedJWT jwt = null;
-        try {
-            jwt = verifier.verify(token);
-        } catch (Exception e) {
-            throw new RuntimeException("登录凭证已过去,请重新登录");
-        }
-
-        return jwt.getClaims();
-    }
-}
+package com.template.common.utils;
+
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.JWTVerifier;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.auth0.jwt.interfaces.Claim;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.template.model.pojo.RepairAdmin;
+import lombok.extern.slf4j.Slf4j;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * jwt 工具
+ **/
+@Slf4j
+public class JWTUtil {
+
+    private static String SIGNATURE = "token!@#$%^7890";
+
+    /**
+     * token过期时间,7天
+     */
+//    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;
+    private static final long EXPIRED = 1000 * 60 * 60 * 24;
+
+    /**
+     * 生成token 有过期时间
+     * @return 返回token
+     */
+    public static String getToken(RepairAdmin ra){
+
+        // 签发时间
+        Date iatDate = new Date();
+
+//        // 过期时间
+//        Calendar nowTime = Calendar.getInstance();
+//        nowTime.add(Calendar.DAY_OF_WEEK, 3);
+//        Date expiresDate = nowTime.getTime();
+
+        Map<String, Object> map = new HashMap<>();
+        map.put("alg", "HMAC256");
+        map.put("typ", "JWT");
+        String token = JWT.create()
+                .withHeader(map) // header
+                .withClaim("account", ra.getAccount()) // 账号
+                .withClaim("password", ra.getPassword()) // 密码
+                .withExpiresAt(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED)) // 设置过期时间。过期时间要大于签发时间
+                .withIssuedAt(iatDate) // 设置签发时间
+                .sign(Algorithm.HMAC256(SIGNATURE)); // 加密
+        return token;
+
+//
+//        JWTCreator.Builder builder = JWT.create();
+//        map.forEach((k,v)->{
+//            builder.withClaim(k,v);
+//        });
+//        Calendar instance = Calendar.getInstance();
+//        instance.add(Calendar.SECOND,7);
+//        builder.withExpiresAt(instance.getTime());
+//        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
+    }
+
+    public static long getExpired() {
+        return EXPIRED;
+    }
+
+
+    /**
+     * 验证token
+     * @param token
+     */
+    public static void verify(String token){
+        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
+    }
+
+    /**
+     * 获取token中payload
+     * @param token
+     * @return
+     */
+    public static DecodedJWT getToken(String token){
+        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
+    }
+
+
+
+    /*
+     * 解密Token
+     * */
+    public static Map<String, Claim> verifyToken(String token)  {
+        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGNATURE)).build();
+        DecodedJWT jwt = null;
+        try {
+            jwt = verifier.verify(token);
+        } catch (Exception e) {
+            throw new RuntimeException("登录凭证已过去,请重新登录");
+        }
+
+        return jwt.getClaims();
+    }
+}

+ 54 - 54
src/main/java/com/template/common/utils/Md5Utils.java

@@ -1,54 +1,54 @@
-package com.template.common.utils;
-
-import com.alibaba.druid.util.Utils;
-
-import java.math.BigInteger;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-public class Md5Utils {
-
-    public static String md5One(String passWord) {
-        byte[] secretBytes = null;
-        try {
-            secretBytes = MessageDigest.getInstance("md5").digest(
-                    passWord.getBytes());
-        } catch (NoSuchAlgorithmException e) {
-            throw new RuntimeException("没有md5这个算法!");
-        }
-        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
-        // 如果生成数字未满32位,需要前面补0
-        for (int i = 0; i < 32 - md5code.length(); i++) {
-            md5code = "0" + md5code;
-        }
-        return md5code;
-    }
-
-    /**
-     * 工具类md5加密
-     * @param password
-     * @return
-     */
-    public static  String md5Two(String password){
-        String s = Utils.md5(password);
-        return s;
-    }
-
-    /**
-     * 可逆的的加密解密方法;两次是解密,一次是加密
-     * @param inStr
-     * @return
-     */
-    public static String convertMD5(String inStr){
-
-        char[] a = inStr.toCharArray();
-        for (int i = 0; i < a.length; i++){
-            a[i] = (char) (a[i] ^ 't');
-        }
-        String s = new String(a);
-        return s;
-
-    }
-
-
-}
+package com.template.common.utils;
+
+import com.alibaba.druid.util.Utils;
+
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+public class Md5Utils {
+
+    public static String md5One(String passWord) {
+        byte[] secretBytes = null;
+        try {
+            secretBytes = MessageDigest.getInstance("md5").digest(
+                    passWord.getBytes());
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException("没有md5这个算法!");
+        }
+        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
+        // 如果生成数字未满32位,需要前面补0
+        for (int i = 0; i < 32 - md5code.length(); i++) {
+            md5code = "0" + md5code;
+        }
+        return md5code;
+    }
+
+    /**
+     * 工具类md5加密
+     * @param password
+     * @return
+     */
+    public static  String md5Two(String password){
+        String s = Utils.md5(password);
+        return s;
+    }
+
+    /**
+     * 可逆的的加密解密方法;两次是解密,一次是加密
+     * @param inStr
+     * @return
+     */
+    public static String convertMD5(String inStr){
+
+        char[] a = inStr.toCharArray();
+        for (int i = 0; i < a.length; i++){
+            a[i] = (char) (a[i] ^ 't');
+        }
+        String s = new String(a);
+        return s;
+
+    }
+
+
+}

File diff suppressed because it is too large
+ 548 - 548
src/main/java/com/template/common/utils/Message.java


+ 113 - 113
src/main/java/com/template/common/utils/Message2.java

@@ -1,113 +1,113 @@
-package com.template.common.utils;
-
-import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
-import com.alibaba.fastjson.JSONObject;
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.StatusLine;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpResponseException;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
-
-
-import java.io.IOException;
-import java.util.HashMap;
-
-/**
- * 公众号,推送信息,推给商家信息
- */
-public class Message2 {
-
-//小程序
-//    static String appId="wx2fc3f45732fae5d3";
-//    static String secret="7eee4a49a4470a77f9222995e8511547";
-
-//公众号
-    static String appId="wxa46ef222053a1047";
-    static String secret="16f74a1265c314fd79fdf90670173467";
-
-    /**
-     * 公众号推送消息
-     * @param openid 公众号openId
-     * @param type  事件
-     * @param location  地点
-     * @param dateTime  时间
-     * @return
-     * @throws Exception
-     */
-    public static String send(String openid,String type,String location,String dateTime)
-            throws Exception {
-
-        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
-
-        String s = HttpsClient.httpsRequestReturnString(url, "GET", "");
-        JSONObject jsonObject = JSONObject.parseObject(s);
-        String access_token = jsonObject.getString("access_token");
-
-
-        JSONObject message = new JSONObject();
-        message.put("touser", openid);
-        message.put("template_id", "vPuSS7nivkQHxcGzpZB-NedVKzqJ4ifk0FTiBI7Aa20");
-
-        JSONObject small = new JSONObject();
-        small.put("appid", "wx2fc3f45732fae5d3");
-        small.put("pagepath", "pages/msgWarn/msgWarn");
-        message.put("miniprogram", small);
-        // 报警类型
-        JSONObject const2 = new JSONObject();
-        const2.put("value", type);
-        const2.put("color", "#173177");
-
-        // 报警位置
-        JSONObject thing3 = new JSONObject();
-        thing3.put("value", location);
-        thing3.put("color", "#173177");
-
-        // 报警时间
-        JSONObject time4 = new JSONObject();
-        time4.put("value", dateTime);
-        time4.put("color", "#173177");
-
-        // 封装data
-        JSONObject data = new JSONObject();
-        data.put("const2",const2);
-        data.put("thing3",thing3);
-        data.put("time4",time4);
-
-        message.put("data",data);
-
-        String s1 = HttpsClient.sendJson("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, message);
-        System.out.println("s1 = " + s1);
-        return s1;
-    }
-
-
-    public static String getToken() throws Exception {
-        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
-
-        String s = HttpsClient.httpsRequestReturnString(url, "GET", "");
-        JSONObject jsonObject = JSONObject.parseObject(s);
-        System.out.println("jsonObject = " + jsonObject);
-        String access_token = jsonObject.getString("access_token");
-//        HttpsClient.httpsRequestReturnString("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token, "POST", message.toJSONString());
-        return access_token;
-    }
-
-
-
-
-    public static void main(String[] args) throws Exception {
-        String o9MsY67wqvQ__o_pOzF7oeN4MQPM = send("o9MsY67wqvQ__o_pOzF7oeN4MQPM","进入区域","IPCamera 01","2024-01-29 16:16:14");
-//        String token = getToken();
-//        System.out.println("token = " + token);
-    }
-}
+package com.template.common.utils;
+
+import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.StatusLine;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpResponseException;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+
+import java.io.IOException;
+import java.util.HashMap;
+
+/**
+ * 公众号,推送信息,推给商家信息
+ */
+public class Message2 {
+
+//小程序
+//    static String appId="wx2fc3f45732fae5d3";
+//    static String secret="7eee4a49a4470a77f9222995e8511547";
+
+//公众号
+    static String appId="wxa46ef222053a1047";
+    static String secret="16f74a1265c314fd79fdf90670173467";
+
+    /**
+     * 公众号推送消息
+     * @param openid 公众号openId
+     * @param type  事件
+     * @param location  地点
+     * @param dateTime  时间
+     * @return
+     * @throws Exception
+     */
+    public static String send(String openid,String type,String location,String dateTime)
+            throws Exception {
+
+        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
+
+        String s = HttpsClient.httpsRequestReturnString(url, "GET", "");
+        JSONObject jsonObject = JSONObject.parseObject(s);
+        String access_token = jsonObject.getString("access_token");
+
+
+        JSONObject message = new JSONObject();
+        message.put("touser", openid);
+        message.put("template_id", "vPuSS7nivkQHxcGzpZB-NedVKzqJ4ifk0FTiBI7Aa20");
+
+        JSONObject small = new JSONObject();
+        small.put("appid", "wx2fc3f45732fae5d3");
+        small.put("pagepath", "pages/msgWarn/msgWarn");
+        message.put("miniprogram", small);
+        // 报警类型
+        JSONObject const2 = new JSONObject();
+        const2.put("value", type);
+        const2.put("color", "#173177");
+
+        // 报警位置
+        JSONObject thing3 = new JSONObject();
+        thing3.put("value", location);
+        thing3.put("color", "#173177");
+
+        // 报警时间
+        JSONObject time4 = new JSONObject();
+        time4.put("value", dateTime);
+        time4.put("color", "#173177");
+
+        // 封装data
+        JSONObject data = new JSONObject();
+        data.put("const2",const2);
+        data.put("thing3",thing3);
+        data.put("time4",time4);
+
+        message.put("data",data);
+
+        String s1 = HttpsClient.sendJson("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, message);
+        System.out.println("s1 = " + s1);
+        return s1;
+    }
+
+
+    public static String getToken() throws Exception {
+        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
+
+        String s = HttpsClient.httpsRequestReturnString(url, "GET", "");
+        JSONObject jsonObject = JSONObject.parseObject(s);
+        System.out.println("jsonObject = " + jsonObject);
+        String access_token = jsonObject.getString("access_token");
+//        HttpsClient.httpsRequestReturnString("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token, "POST", message.toJSONString());
+        return access_token;
+    }
+
+
+
+
+    public static void main(String[] args) throws Exception {
+        String o9MsY67wqvQ__o_pOzF7oeN4MQPM = send("o9MsY67wqvQ__o_pOzF7oeN4MQPM","进入区域","IPCamera 01","2024-01-29 16:16:14");
+//        String token = getToken();
+//        System.out.println("token = " + token);
+    }
+}

+ 23 - 23
src/main/java/com/template/common/utils/MyX509TrustManager.java

@@ -1,23 +1,23 @@
-package com.template.common.utils;
-
-import javax.net.ssl.X509TrustManager;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-/**
- * X509TrustManager用于实现SSL证书的安全校验
- * @author lujunjie
- * @date   2018/03/01
- */
-public class MyX509TrustManager implements X509TrustManager {
-    @Override
-    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
-
-    @Override
-    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
-
-    @Override
-    public X509Certificate[] getAcceptedIssuers() {
-        return null;
-    }
-}
+package com.template.common.utils;
+
+import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * X509TrustManager用于实现SSL证书的安全校验
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class MyX509TrustManager implements X509TrustManager {
+    @Override
+    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public X509Certificate[] getAcceptedIssuers() {
+        return null;
+    }
+}

+ 99 - 99
src/main/java/com/template/common/utils/PropertiesUtil.java

@@ -1,99 +1,99 @@
-package com.template.common.utils;
-
-import java.io.*;
-import java.net.URI;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * <p>Title: PropertiesUtil</p>
- * <p>Description: properties资源文件解析工具</p>
- * @author fengyong
- * @date 2018年9月7日
- */
-public class PropertiesUtil {
-
-	private static Properties props = null;
-	private static URI uri;
-	private static String fileName = "/application.properties";
-	
-	private static InputStream in = null;
-
-	static {
-		try {
-			props = new Properties();
-			InputStream fis = PropertiesUtil.class.getResourceAsStream(fileName);
-			props.load(fis);
-			uri = PropertiesUtil.class.getResource(fileName).toURI();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-	/**
-	 * 获取某个属性
-	 */
-	public static String getProperty(String key) {
-		try {
-			props.load(PropertiesUtil.class.getResourceAsStream(fileName));
-		} catch (IOException e) {
-			e.printStackTrace();
-		}
-		return props.getProperty(key);
-	}
-
-	/**
-	 * 获取所有属性,返回一个map,不常用 可以试试props.putAll(t)
-	 */
-	@SuppressWarnings("rawtypes")
-	public static Map<String, String> getAllProperty() {
-		Map<String, String> map = new HashMap<String, String>();
-		Enumeration enu = props.propertyNames();
-		while (enu.hasMoreElements()) {
-			String key = (String) enu.nextElement();
-			String value = props.getProperty(key);
-			map.put(key, value);
-		}
-		return map;
-	}
-
-	/**
-	 * 在控制台上打印出所有属性,调试时用。
-	 */
-	public static void printProperties() {
-		props.list(System.out);
-	}
-
-	/**
-	 * 写入properties信息
-	 */
-	public static void writeProperties(String key, String value) {
-		try {
-			OutputStream fos = new FileOutputStream(new File(uri));
-			props.setProperty(key, value);
-			// 将此 Properties 表中的属性列表(键和元素对)写入输出流
-			props.store(fos, "『comments』Update key:" + key);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-	
-	/**
-	 * 取默认key的value
-	 * */
-	public static String getValue(String key){
-		String value = null;
-		props = new Properties();
-		in = PropertiesUtil.class.getResourceAsStream(fileName);
-		try {
-			props.load(in);
-		} catch (IOException e) {
-//			e.printStackTrace();
-		}
-		value = (String) props.get(key);
-		return value;
-	}
-
-}
+package com.template.common.utils;
+
+import java.io.*;
+import java.net.URI;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * <p>Title: PropertiesUtil</p>
+ * <p>Description: properties资源文件解析工具</p>
+ * @author fengyong
+ * @date 2018年9月7日
+ */
+public class PropertiesUtil {
+
+	private static Properties props = null;
+	private static URI uri;
+	private static String fileName = "/application.properties";
+	
+	private static InputStream in = null;
+
+	static {
+		try {
+			props = new Properties();
+			InputStream fis = PropertiesUtil.class.getResourceAsStream(fileName);
+			props.load(fis);
+			uri = PropertiesUtil.class.getResource(fileName).toURI();
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * 获取某个属性
+	 */
+	public static String getProperty(String key) {
+		try {
+			props.load(PropertiesUtil.class.getResourceAsStream(fileName));
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return props.getProperty(key);
+	}
+
+	/**
+	 * 获取所有属性,返回一个map,不常用 可以试试props.putAll(t)
+	 */
+	@SuppressWarnings("rawtypes")
+	public static Map<String, String> getAllProperty() {
+		Map<String, String> map = new HashMap<String, String>();
+		Enumeration enu = props.propertyNames();
+		while (enu.hasMoreElements()) {
+			String key = (String) enu.nextElement();
+			String value = props.getProperty(key);
+			map.put(key, value);
+		}
+		return map;
+	}
+
+	/**
+	 * 在控制台上打印出所有属性,调试时用。
+	 */
+	public static void printProperties() {
+		props.list(System.out);
+	}
+
+	/**
+	 * 写入properties信息
+	 */
+	public static void writeProperties(String key, String value) {
+		try {
+			OutputStream fos = new FileOutputStream(new File(uri));
+			props.setProperty(key, value);
+			// 将此 Properties 表中的属性列表(键和元素对)写入输出流
+			props.store(fos, "『comments』Update key:" + key);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+	
+	/**
+	 * 取默认key的value
+	 * */
+	public static String getValue(String key){
+		String value = null;
+		props = new Properties();
+		in = PropertiesUtil.class.getResourceAsStream(fileName);
+		try {
+			props.load(in);
+		} catch (IOException e) {
+//			e.printStackTrace();
+		}
+		value = (String) props.get(key);
+		return value;
+	}
+
+}

File diff suppressed because it is too large
+ 196 - 196
src/main/java/com/template/common/utils/RSAUtils.java


+ 32 - 32
src/main/java/com/template/common/utils/RandomTrackAlgorithm.java

@@ -1,32 +1,32 @@
-package com.template.common.utils;
-
-import com.alibaba.fastjson.JSONObject;
-
-import java.math.BigDecimal;
-import java.util.*;
-
-public class RandomTrackAlgorithm {
-
-    public static BigDecimal makeRandom(float max, float min, int scale){
-        BigDecimal cha = new BigDecimal(Math.random() * (max-min) + min);
-        return cha.setScale(scale,BigDecimal.ROUND_HALF_UP);//保留 scale 位小数,并四舍五入
-    }
-
-    public static List<List<BigDecimal>> getPosition(){
-        List<List<BigDecimal>> all = new ArrayList<>();
-        // 生成随机坐标点
-        BigDecimal x = null;
-        BigDecimal y = null;
-        for (int i = 0; i < 10; i++) {
-            List<BigDecimal> list = new LinkedList<>();
-            // 114.449557,28.109357
-            x = makeRandom(0.001f,0.000001f,6).add(BigDecimal.valueOf(114.449557));
-            y = makeRandom(0.001f,0.000001f,6).add(BigDecimal.valueOf(28.109357));
-            list.add(x);
-            list.add(y);
-            all.add(list);
-        }
-        return all;
-    }
-
-}
+package com.template.common.utils;
+
+import com.alibaba.fastjson.JSONObject;
+
+import java.math.BigDecimal;
+import java.util.*;
+
+public class RandomTrackAlgorithm {
+
+    public static BigDecimal makeRandom(float max, float min, int scale){
+        BigDecimal cha = new BigDecimal(Math.random() * (max-min) + min);
+        return cha.setScale(scale,BigDecimal.ROUND_HALF_UP);//保留 scale 位小数,并四舍五入
+    }
+
+    public static List<List<BigDecimal>> getPosition(){
+        List<List<BigDecimal>> all = new ArrayList<>();
+        // 生成随机坐标点
+        BigDecimal x = null;
+        BigDecimal y = null;
+        for (int i = 0; i < 10; i++) {
+            List<BigDecimal> list = new LinkedList<>();
+            // 114.449557,28.109357
+            x = makeRandom(0.001f,0.000001f,6).add(BigDecimal.valueOf(114.449557));
+            y = makeRandom(0.001f,0.000001f,6).add(BigDecimal.valueOf(28.109357));
+            list.add(x);
+            list.add(y);
+            all.add(list);
+        }
+        return all;
+    }
+
+}

+ 126 - 126
src/main/java/com/template/common/utils/RequestUtils.java

@@ -1,126 +1,126 @@
-package com.template.common.utils;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @Author: binguo
- * @Date: 2023/12/21 星期四 9:39
- * @Description: com.template.common.utils
- * @Version: 1.0
- */
-public class RequestUtils {
-    /**
-     * GET请求
-     * @param url 请求地址
-     * @param param 请求参数
-     * @return
-     */
-    public static String httpGet(String url,String param){
-        String result = "";
-        BufferedReader in = null;
-        try {
-            String urlNameString = url + "?" + param;
-            URL realUrl = new URL(urlNameString);
-            // 打开和URL之间的连接
-            URLConnection connection = realUrl.openConnection();
-            // 设置通用的请求属性
-            connection.setRequestProperty("accept", "*/*");
-            connection.setRequestProperty("connection", "Keep-Alive");
-            connection.setRequestProperty("user-agent",
-                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-            // 建立实际的连接
-            connection.connect();
-            // 获取所有响应头字段
-            Map<String, List<String>> map = connection.getHeaderFields();
-            // 遍历所有的响应头字段
-            for (String key : map.keySet()) {
-                System.out.println(key + "--->" + map.get(key));
-            }
-            // 定义 BufferedReader输入流来读取URL的响应
-            in = new BufferedReader(new InputStreamReader(
-                    connection.getInputStream()));
-            String line;
-            while ((line = in.readLine()) != null) {
-                result += line;
-            }
-        } catch (Exception e) {
-            System.out.println("发送GET请求出现异常!" + e);
-            e.printStackTrace();
-        }
-        // 使用finally块来关闭输入流
-        finally {
-            try {
-                if (in != null) {
-                    in.close();
-                }
-            } catch (Exception e2) {
-                e2.printStackTrace();
-            }
-        }
-        return result;
-    }
-
-
-    /**
-     * POST请求
-     * @param url 请求的url
-     * @param param 参数
-     * @return
-     */
-    public static String httpPost(String url, String param){
-        String dummyData = param.replace("%", "").replace(",", "").replace(" ", "+").replace("/","");
-        PrintWriter out = null;
-        BufferedReader in = null;
-        String result = "";
-        try {
-            URL realUrl = new URL(url);
-            // 打开和URL之间的连接
-            URLConnection conn = realUrl.openConnection();
-            // 设置通用的请求属性
-            conn.setRequestProperty("accept", "*/*");
-            conn.setRequestProperty("connection", "Keep-Alive");
-            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-            conn.setRequestProperty("Content-Type", "application/json");
-            // 发送POST请求必须设置如下两行
-            conn.setDoOutput(true);
-            conn.setDoInput(true);
-            // 获取URLConnection对象对应的输出流
-            out = new PrintWriter(conn.getOutputStream());
-            // 发送请求参数
-            out.print(param);
-            // flush输出流的缓冲
-            out.flush();
-            // 定义BufferedReader输入流来读取URL的响应
-            in = new BufferedReader(
-                    new InputStreamReader(conn.getInputStream()));
-            String line;
-            while ((line = in.readLine()) != null) {
-                result += line;
-            }
-        } catch (Exception e) {
-            System.out.println("发送 POST 请求出现异常!" + e);
-            e.printStackTrace();
-        }
-        //使用finally块来关闭输出流、输入流
-        finally {
-            try {
-                if (out != null) {
-                    out.close();
-                }
-                if (in != null) {
-                    in.close();
-                }
-            } catch (IOException ex) {
-                ex.printStackTrace();
-            }
-        }
-        return result;
-    }
-}
+package com.template.common.utils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/12/21 星期四 9:39
+ * @Description: com.template.common.utils
+ * @Version: 1.0
+ */
+public class RequestUtils {
+    /**
+     * GET请求
+     * @param url 请求地址
+     * @param param 请求参数
+     * @return
+     */
+    public static String httpGet(String url,String param){
+        String result = "";
+        BufferedReader in = null;
+        try {
+            String urlNameString = url + "?" + param;
+            URL realUrl = new URL(urlNameString);
+            // 打开和URL之间的连接
+            URLConnection connection = realUrl.openConnection();
+            // 设置通用的请求属性
+            connection.setRequestProperty("accept", "*/*");
+            connection.setRequestProperty("connection", "Keep-Alive");
+            connection.setRequestProperty("user-agent",
+                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
+            // 建立实际的连接
+            connection.connect();
+            // 获取所有响应头字段
+            Map<String, List<String>> map = connection.getHeaderFields();
+            // 遍历所有的响应头字段
+            for (String key : map.keySet()) {
+                System.out.println(key + "--->" + map.get(key));
+            }
+            // 定义 BufferedReader输入流来读取URL的响应
+            in = new BufferedReader(new InputStreamReader(
+                    connection.getInputStream()));
+            String line;
+            while ((line = in.readLine()) != null) {
+                result += line;
+            }
+        } catch (Exception e) {
+            System.out.println("发送GET请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        // 使用finally块来关闭输入流
+        finally {
+            try {
+                if (in != null) {
+                    in.close();
+                }
+            } catch (Exception e2) {
+                e2.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+
+    /**
+     * POST请求
+     * @param url 请求的url
+     * @param param 参数
+     * @return
+     */
+    public static String httpPost(String url, String param){
+        String dummyData = param.replace("%", "").replace(",", "").replace(" ", "+").replace("/","");
+        PrintWriter out = null;
+        BufferedReader in = null;
+        String result = "";
+        try {
+            URL realUrl = new URL(url);
+            // 打开和URL之间的连接
+            URLConnection conn = realUrl.openConnection();
+            // 设置通用的请求属性
+            conn.setRequestProperty("accept", "*/*");
+            conn.setRequestProperty("connection", "Keep-Alive");
+            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
+            conn.setRequestProperty("Content-Type", "application/json");
+            // 发送POST请求必须设置如下两行
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(conn.getOutputStream());
+            // 发送请求参数
+            out.print(param);
+            // flush输出流的缓冲
+            out.flush();
+            // 定义BufferedReader输入流来读取URL的响应
+            in = new BufferedReader(
+                    new InputStreamReader(conn.getInputStream()));
+            String line;
+            while ((line = in.readLine()) != null) {
+                result += line;
+            }
+        } catch (Exception e) {
+            System.out.println("发送 POST 请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        //使用finally块来关闭输出流、输入流
+        finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        return result;
+    }
+}

+ 42 - 42
src/main/java/com/template/common/utils/SHA1.java

@@ -1,42 +1,42 @@
-package com.template.common.utils;
-import java.security.MessageDigest;
-
-/**
- * 微信SHA1算法
- * @author lujunjie
- * @date   2018/03/01
- */
-public final class SHA1 {
-
-    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
-
-    /**
-     *  将字节并格式化
-     * @param bytes 原始字节
-     * @return 格式化字节
-     */
-    private static String getFormattedText(byte[] bytes) {
-        int len = bytes.length;
-        StringBuilder buf = new StringBuilder(len * 2);
-        // 把密文转换成十六进制的字符串形式
-        for (int j = 0; j < len; j++) {
-            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
-            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
-        }
-        return buf.toString();
-    }
-
-    public static String encode(String str) {
-        if (str == null) {
-            return null;
-        }
-        try {
-            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
-            messageDigest.update(str.getBytes());
-            return getFormattedText(messageDigest.digest());
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-}
+package com.template.common.utils;
+import java.security.MessageDigest;
+
+/**
+ * 微信SHA1算法
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public final class SHA1 {
+
+    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     *  将字节并格式化
+     * @param bytes 原始字节
+     * @return 格式化字节
+     */
+    private static String getFormattedText(byte[] bytes) {
+        int len = bytes.length;
+        StringBuilder buf = new StringBuilder(len * 2);
+        // 把密文转换成十六进制的字符串形式
+        for (int j = 0; j < len; j++) {
+            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
+            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
+        }
+        return buf.toString();
+    }
+
+    public static String encode(String str) {
+        if (str == null) {
+            return null;
+        }
+        try {
+            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
+            messageDigest.update(str.getBytes());
+            return getFormattedText(messageDigest.digest());
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+}

+ 213 - 213
src/main/java/com/template/common/utils/SendSms.java

@@ -1,213 +1,213 @@
-package com.template.common.utils;
-
-
-import com.tencentcloudapi.common.Credential;
-import com.tencentcloudapi.common.exception.TencentCloudSDKException;
-
-//导入可选配置类
-import com.tencentcloudapi.common.profile.ClientProfile;
-import com.tencentcloudapi.common.profile.HttpProfile;
-
-// 导入对应SMS模块的client
-import com.tencentcloudapi.sms.v20210111.SmsClient;
-
-// 导入要请求接口对应的request response类
-import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
-import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
-import com.tencentcloudapi.sms.v20210111.models.SendStatus;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-
-import java.util.Date;
-
-/**
- * Tencent Cloud Sms Sendsms
- */
-public class SendSms {
-
-
-    //腾讯云上的签名
-//    private static String secretID="AKIDDPo13qZCZqtgJsGQL7AyYu1wc7QVMyLl";
-    private static String secretID = "AKIDCPVZdcWIxgHpy5FYxVyPiqkZGrhdXUBg";
-
-    //腾讯云上的密钥
-//    private static String secretKey="JPGrELFySiv0pOrKOPEwSnulOq9IPPDr";
-    private static String secretKey = "NkyCN3cz97qKaeXLvHOGxOcdS8f184pL";
-
-    //短信应用id
-//    private static String sdkAppid="1400813506";
-    private static String sdkAppid = "1400885930";
-
-    //短信签名内容
-//    private static String signName="华仁享学教育";
-    private static String signName = "江西省创海科技有限公司";
-
-    //模板Id
-//    private static String templateId="1770016";
-    private static String templateId = "2060673"; //验证码
-    private static String templateId2 = "2065770"; //预约短信
-
-    //验证码有效时长
-    private static String smsMin = "1";
-
-
-    public static String sendSms(String phoneNumber, String code) {
-        String returString = "";
-        try {
-            /* 必要步骤:
-             * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
-             * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
-             * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
-             * 以免泄露密钥对危及你的财产安全。
-             * SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi */
-//            Credential cred = new Credential(smsConfig.getSecretID(), smsConfig.getSecretKey());
-            Credential cred = new Credential(secretID, secretKey);
-
-            // 实例化一个http选项,可选,没有特殊需求可以跳过
-            HttpProfile httpProfile = new HttpProfile();
-            // 设置代理(无需要直接忽略)
-            // httpProfile.setProxyHost("真实代理ip");
-            // httpProfile.setProxyPort(真实代理端口);
-            /* SDK默认使用POST方法。
-             * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
-            httpProfile.setReqMethod("POST");
-            /* SDK有默认的超时时间,非必要请不要进行调整
-             * 如有需要请在代码中查阅以获取最新的默认值 */
-            httpProfile.setConnTimeout(60);
-            /* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
-            httpProfile.setEndpoint("sms.tencentcloudapi.com");
-
-            /* 非必要步骤:
-             * 实例化一个客户端配置对象,可以指定超时时间等配置 */
-            ClientProfile clientProfile = new ClientProfile();
-            /* SDK默认用TC3-HMAC-SHA256进行签名
-             * 非必要请不要修改这个字段 */
-            clientProfile.setSignMethod("HmacSHA256");
-            clientProfile.setHttpProfile(httpProfile);
-            /* 实例化要请求产品(以sms为例)的client对象
-             * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
-            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
-            /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
-             * 你可以直接查询SDK源码确定接口有哪些属性可以设置
-             * 属性可能是基本类型,也可能引用了另一个数据结构
-             * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
-            SendSmsRequest req = new SendSmsRequest();
-
-            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
-             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
-             * 基本类型的设置:
-             * 帮助链接:
-             * 短信控制台: https://console.cloud.tencent.com/smsv2
-             * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
-
-            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
-            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
-//            String sdkAppId = "1400009099";
-//            req.setSmsSdkAppId(smsConfig.getSdkAppid());
-            req.setSmsSdkAppId(sdkAppid);
-
-            /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
-            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
-//            String signName = "腾讯云";
-//            req.setSignName(smsConfig.getSignName());
-            req.setSignName(signName);
-
-            /* 模板 ID: 必须填写已审核通过的模板 ID */
-            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
-//            String templateId = "449739";
-//            req.setTemplateId(smsConfig.getTemplateId());
-            req.setTemplateId(templateId);
-
-
-            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
-//           第一个为验证码,第二个为有效时间
-//            String[] templateParamSet = {code,smsConfig.getSmsMin()};
-            String[] templateParamSet = {code, "1"};
-            req.setTemplateParamSet(templateParamSet);
-
-            /* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
-             * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */
-//            String[] phoneNumberSet = {"+8621212313123", "+8612345678902", "+8612345678903"};
-            String[] phoneNumbers = {phoneNumber};
-            req.setPhoneNumberSet(phoneNumbers);
-
-            /* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
-//            String sessionContext = "";
-//            req.setSessionContext(sessionContext);
-
-            /* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
-//            String extendCode = "";
-//            req.setExtendCode(extendCode);
-
-            /* 国际/港澳台短信 SenderId(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] */
-//            String senderid = "";
-//            req.setSenderId(senderid);
-
-            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
-             * 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
-            SendSmsResponse res = client.SendSms(req);
-
-            // 输出json格式的字符串回包
-//            System.out.println(SendSmsResponse.toJsonString(res));
-
-            // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
-            // System.out.println(res.getRequestId());
-
-            /* 当出现以下错误码时,快速解决方案参考
-             * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
-             * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
-             * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
-             * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
-             * 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
-             */
-            SendStatus sendStatus = res.getSendStatusSet()[0];
-            System.out.println(sendStatus.getMessage());
-//            System.out.println("sendStatus = " + sendStatus);
-            returString = sendStatus.getMessage();
-        } catch (TencentCloudSDKException e) {
-            e.printStackTrace();
-        }
-        return returString;
-    }
-
-
-    public static String sendVisitorSms(String phoneNumber, String year, String month, String day, String startTime, String endTime, String code) {
-        String returString = "";
-        try {
-            Credential cred = new Credential(secretID, secretKey);
-
-            HttpProfile httpProfile = new HttpProfile();
-            httpProfile.setReqMethod("POST");
-            httpProfile.setConnTimeout(60);
-            httpProfile.setEndpoint("sms.tencentcloudapi.com");
-            ClientProfile clientProfile = new ClientProfile();
-            clientProfile.setSignMethod("HmacSHA256");
-            clientProfile.setHttpProfile(httpProfile);
-            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
-            SendSmsRequest req = new SendSmsRequest();
-            req.setSmsSdkAppId(sdkAppid);
-            req.setSignName(signName);
-            req.setTemplateId(templateId2);
-            String[] templateParamSet = {year, month, day, startTime, endTime, code};
-            req.setTemplateParamSet(templateParamSet);
-            String[] phoneNumbers = {phoneNumber};
-            req.setPhoneNumberSet(phoneNumbers);
-            SendSmsResponse res = client.SendSms(req);
-            SendStatus sendStatus = res.getSendStatusSet()[0];
-            System.out.println(sendStatus.getMessage());
-            returString = sendStatus.getMessage();
-        } catch (TencentCloudSDKException e) {
-            e.printStackTrace();
-        }
-        return returString;
-    }
-
-    public static void main(String[] args) throws TencentCloudSDKException {
-        //这里定义一个存储电话号码的数组
-
-        String tels = "+8618279193722"; // 手机号前面记得带上国家区域编码
-        String test = sendSms("+8618279193722", "123456");
-
-    }
-
-}
+package com.template.common.utils;
+
+
+import com.tencentcloudapi.common.Credential;
+import com.tencentcloudapi.common.exception.TencentCloudSDKException;
+
+//导入可选配置类
+import com.tencentcloudapi.common.profile.ClientProfile;
+import com.tencentcloudapi.common.profile.HttpProfile;
+
+// 导入对应SMS模块的client
+import com.tencentcloudapi.sms.v20210111.SmsClient;
+
+// 导入要请求接口对应的request response类
+import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
+import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
+import com.tencentcloudapi.sms.v20210111.models.SendStatus;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+
+import java.util.Date;
+
+/**
+ * Tencent Cloud Sms Sendsms
+ */
+public class SendSms {
+
+
+    //腾讯云上的签名
+//    private static String secretID="AKIDDPo13qZCZqtgJsGQL7AyYu1wc7QVMyLl";
+    private static String secretID = "AKIDCPVZdcWIxgHpy5FYxVyPiqkZGrhdXUBg";
+
+    //腾讯云上的密钥
+//    private static String secretKey="JPGrELFySiv0pOrKOPEwSnulOq9IPPDr";
+    private static String secretKey = "NkyCN3cz97qKaeXLvHOGxOcdS8f184pL";
+
+    //短信应用id
+//    private static String sdkAppid="1400813506";
+    private static String sdkAppid = "1400885930";
+
+    //短信签名内容
+//    private static String signName="华仁享学教育";
+    private static String signName = "江西省创海科技有限公司";
+
+    //模板Id
+//    private static String templateId="1770016";
+    private static String templateId = "2060673"; //验证码
+    private static String templateId2 = "2065770"; //预约短信
+
+    //验证码有效时长
+    private static String smsMin = "1";
+
+
+    public static String sendSms(String phoneNumber, String code) {
+        String returString = "";
+        try {
+            /* 必要步骤:
+             * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
+             * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
+             * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
+             * 以免泄露密钥对危及你的财产安全。
+             * SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi */
+//            Credential cred = new Credential(smsConfig.getSecretID(), smsConfig.getSecretKey());
+            Credential cred = new Credential(secretID, secretKey);
+
+            // 实例化一个http选项,可选,没有特殊需求可以跳过
+            HttpProfile httpProfile = new HttpProfile();
+            // 设置代理(无需要直接忽略)
+            // httpProfile.setProxyHost("真实代理ip");
+            // httpProfile.setProxyPort(真实代理端口);
+            /* SDK默认使用POST方法。
+             * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
+            httpProfile.setReqMethod("POST");
+            /* SDK有默认的超时时间,非必要请不要进行调整
+             * 如有需要请在代码中查阅以获取最新的默认值 */
+            httpProfile.setConnTimeout(60);
+            /* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
+            httpProfile.setEndpoint("sms.tencentcloudapi.com");
+
+            /* 非必要步骤:
+             * 实例化一个客户端配置对象,可以指定超时时间等配置 */
+            ClientProfile clientProfile = new ClientProfile();
+            /* SDK默认用TC3-HMAC-SHA256进行签名
+             * 非必要请不要修改这个字段 */
+            clientProfile.setSignMethod("HmacSHA256");
+            clientProfile.setHttpProfile(httpProfile);
+            /* 实例化要请求产品(以sms为例)的client对象
+             * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
+            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
+            /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
+             * 你可以直接查询SDK源码确定接口有哪些属性可以设置
+             * 属性可能是基本类型,也可能引用了另一个数据结构
+             * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
+            SendSmsRequest req = new SendSmsRequest();
+
+            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
+             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
+             * 基本类型的设置:
+             * 帮助链接:
+             * 短信控制台: https://console.cloud.tencent.com/smsv2
+             * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
+
+            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
+            // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
+//            String sdkAppId = "1400009099";
+//            req.setSmsSdkAppId(smsConfig.getSdkAppid());
+            req.setSmsSdkAppId(sdkAppid);
+
+            /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
+            // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
+//            String signName = "腾讯云";
+//            req.setSignName(smsConfig.getSignName());
+            req.setSignName(signName);
+
+            /* 模板 ID: 必须填写已审核通过的模板 ID */
+            // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
+//            String templateId = "449739";
+//            req.setTemplateId(smsConfig.getTemplateId());
+            req.setTemplateId(templateId);
+
+
+            /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
+//           第一个为验证码,第二个为有效时间
+//            String[] templateParamSet = {code,smsConfig.getSmsMin()};
+            String[] templateParamSet = {code, "1"};
+            req.setTemplateParamSet(templateParamSet);
+
+            /* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
+             * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */
+//            String[] phoneNumberSet = {"+8621212313123", "+8612345678902", "+8612345678903"};
+            String[] phoneNumbers = {phoneNumber};
+            req.setPhoneNumberSet(phoneNumbers);
+
+            /* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
+//            String sessionContext = "";
+//            req.setSessionContext(sessionContext);
+
+            /* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */
+//            String extendCode = "";
+//            req.setExtendCode(extendCode);
+
+            /* 国际/港澳台短信 SenderId(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] */
+//            String senderid = "";
+//            req.setSenderId(senderid);
+
+            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
+             * 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
+            SendSmsResponse res = client.SendSms(req);
+
+            // 输出json格式的字符串回包
+//            System.out.println(SendSmsResponse.toJsonString(res));
+
+            // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
+            // System.out.println(res.getRequestId());
+
+            /* 当出现以下错误码时,快速解决方案参考
+             * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
+             * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
+             * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
+             * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
+             * 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
+             */
+            SendStatus sendStatus = res.getSendStatusSet()[0];
+            System.out.println(sendStatus.getMessage());
+//            System.out.println("sendStatus = " + sendStatus);
+            returString = sendStatus.getMessage();
+        } catch (TencentCloudSDKException e) {
+            e.printStackTrace();
+        }
+        return returString;
+    }
+
+
+    public static String sendVisitorSms(String phoneNumber, String year, String month, String day, String startTime, String endTime, String code) {
+        String returString = "";
+        try {
+            Credential cred = new Credential(secretID, secretKey);
+
+            HttpProfile httpProfile = new HttpProfile();
+            httpProfile.setReqMethod("POST");
+            httpProfile.setConnTimeout(60);
+            httpProfile.setEndpoint("sms.tencentcloudapi.com");
+            ClientProfile clientProfile = new ClientProfile();
+            clientProfile.setSignMethod("HmacSHA256");
+            clientProfile.setHttpProfile(httpProfile);
+            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
+            SendSmsRequest req = new SendSmsRequest();
+            req.setSmsSdkAppId(sdkAppid);
+            req.setSignName(signName);
+            req.setTemplateId(templateId2);
+            String[] templateParamSet = {year, month, day, startTime, endTime, code};
+            req.setTemplateParamSet(templateParamSet);
+            String[] phoneNumbers = {phoneNumber};
+            req.setPhoneNumberSet(phoneNumbers);
+            SendSmsResponse res = client.SendSms(req);
+            SendStatus sendStatus = res.getSendStatusSet()[0];
+            System.out.println(sendStatus.getMessage());
+            returString = sendStatus.getMessage();
+        } catch (TencentCloudSDKException e) {
+            e.printStackTrace();
+        }
+        return returString;
+    }
+
+    public static void main(String[] args) throws TencentCloudSDKException {
+        //这里定义一个存储电话号码的数组
+
+        String tels = "+8618279193722"; // 手机号前面记得带上国家区域编码
+        String test = sendSms("+8618279193722", "123456");
+
+    }
+
+}

File diff suppressed because it is too large
+ 748 - 748
src/main/java/com/template/common/utils/TimeExchange.java


File diff suppressed because it is too large
+ 628 - 628
src/main/java/com/template/common/utils/TimeExchange2.java


+ 25 - 25
src/main/java/com/template/common/utils/UUIDUtil.java

@@ -1,25 +1,25 @@
-package com.template.common.utils;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Random;
-
-public class UUIDUtil {
-
-    public static long generateID(){
-
-        Random r = new Random();
-        long numbers = 1000000000L + (long)(r.nextDouble() * 999999999L);
-
-        return numbers;
-    }
-
-    public static String getNewDate(){
-        Date nowDate = new Date();// 取当前时间
-        SimpleDateFormat dateFormat = new SimpleDateFormat(
-                "yyyy-MM-dd HH:mm:ss"); // 转换时间格式
-        String date = dateFormat.format(nowDate);
-        return date;
-    }
-
-}
+package com.template.common.utils;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Random;
+
+public class UUIDUtil {
+
+    public static long generateID(){
+
+        Random r = new Random();
+        long numbers = 1000000000L + (long)(r.nextDouble() * 999999999L);
+
+        return numbers;
+    }
+
+    public static String getNewDate(){
+        Date nowDate = new Date();// 取当前时间
+        SimpleDateFormat dateFormat = new SimpleDateFormat(
+                "yyyy-MM-dd HH:mm:ss"); // 转换时间格式
+        String date = dateFormat.format(nowDate);
+        return date;
+    }
+
+}

+ 25 - 25
src/main/java/com/template/common/utils/ValidateCode.java

@@ -1,25 +1,25 @@
-package com.template.common.utils;
-
-import java.util.Random;
-
-//验证码随机数
-public  class  ValidateCode {
-
-   public static Integer generateValidateCode(int length){
-       Integer code =null;
-       if(length == 4){
-           code = new Random().nextInt(9999);//生成随机数,最大为9999
-           if(code < 1000){
-               code = code + 1000;//保证随机数为4位数字
-           }
-       }else if(length == 6){
-           code = new Random().nextInt(999999);//生成随机数,最大为999999
-           if(code < 100000){
-               code = code + 100000;//保证随机数为6位数字
-           }
-       }else{
-           throw new RuntimeException("只能生成4位或6位数字验证码");
-       }
-       return code;
-   }
-}
+package com.template.common.utils;
+
+import java.util.Random;
+
+//验证码随机数
+public  class  ValidateCode {
+
+   public static Integer generateValidateCode(int length){
+       Integer code =null;
+       if(length == 4){
+           code = new Random().nextInt(9999);//生成随机数,最大为9999
+           if(code < 1000){
+               code = code + 1000;//保证随机数为4位数字
+           }
+       }else if(length == 6){
+           code = new Random().nextInt(999999);//生成随机数,最大为999999
+           if(code < 100000){
+               code = code + 100000;//保证随机数为6位数字
+           }
+       }else{
+           throw new RuntimeException("只能生成4位或6位数字验证码");
+       }
+       return code;
+   }
+}

+ 52 - 52
src/main/java/com/template/common/utils/WxConfig.java

@@ -1,52 +1,52 @@
-package com.template.common.utils;
-
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-
-/**
- * 微信公众号开发配置类
- * @author lujunjie
- * @date   2018/03/01
- */
-@Component
-public class WxConfig {
-
-    /**
-     * 开发者ID
-     */
-    public static String apicode = "CS0001";
-
-    /**
-     * 商户号
-     */
-    public static String apikey  = "XMZnRsZe61hEXyYa7JuAtUupJZ2Q5byc";
-
-
-    /**
-     * 统一下单-通知链接
-     */
-    public static String unifiedorderNotifyUrl = "https://app.dev.9kbs.com/";
-
-
-    /**
-     * 连接超时时间
-     */
-    public static Integer connectionTimeout = 15000;
-
-    /**
-     * 连接超时时间
-     */
-    public static Integer readTimeout = 15000;
-
-    //支付map缓存处理
-    private static HashMap<String,String> payMap = new HashMap<String,String>();
-    public static String getPayMap(String key) {
-        return payMap.get(key);
-    }
-    public static void setPayMap(String key,String value) {
-        payMap.put(key,value);
-    }
-
-
-}
+package com.template.common.utils;
+
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+
+/**
+ * 微信公众号开发配置类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+@Component
+public class WxConfig {
+
+    /**
+     * 开发者ID
+     */
+    public static String apicode = "CS0001";
+
+    /**
+     * 商户号
+     */
+    public static String apikey  = "XMZnRsZe61hEXyYa7JuAtUupJZ2Q5byc";
+
+
+    /**
+     * 统一下单-通知链接
+     */
+    public static String unifiedorderNotifyUrl = "https://app.dev.9kbs.com/";
+
+
+    /**
+     * 连接超时时间
+     */
+    public static Integer connectionTimeout = 15000;
+
+    /**
+     * 连接超时时间
+     */
+    public static Integer readTimeout = 15000;
+
+    //支付map缓存处理
+    private static HashMap<String,String> payMap = new HashMap<String,String>();
+    public static String getPayMap(String key) {
+        return payMap.get(key);
+    }
+    public static void setPayMap(String key,String value) {
+        payMap.put(key,value);
+    }
+
+
+}

+ 53 - 53
src/main/java/com/template/common/utils/WxConstants.java

@@ -1,53 +1,53 @@
-package com.template.common.utils;
-
-/**
- * 微信公众号常量类
- * @author lujunjie
- * @date   2018/06/28
- */
-public class WxConstants {
-
-    /**
-     * 默认编码
-     */
-    public static final String DEFAULT_CHARSET = "UTF-8";
-
-    /**
-     * 统一下单-扫描支付
-     */
-    public static String PAY_UNIFIEDORDER = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode";
-
-    public static String Test = "http://localhost:8088/HotWaters/userget_stu.action";
-
-    public static String Test2 = "http://localhost:8088/HotWaters/userstu_info.action";
-
-    /**
-     * 请求成功返回码
-     */
-    public final static String ERRCODE_OK_CODE = "0";
-    /**
-     * 错误的返回码的Key
-     */
-    public final static String ERRCODE = "errcode";
-
-    /**
-     * 返回状态码
-     */
-    public final static String RETURN_CODE= "return_code";
-
-    /**
-     * access_token 字符串
-     */
-    public final static String ACCESS_TOKEN = "access_token";
-
-    /**
-     * 签名类型 MD5
-     */
-    public final static String SING_MD5 = "MD5";
-
-    /**
-     * 签名类型 HMAC-SHA256
-     */
-    public final static String SING_HMACSHA256 = "HMAC-SHA256";
-
-}
+package com.template.common.utils;
+
+/**
+ * 微信公众号常量类
+ * @author lujunjie
+ * @date   2018/06/28
+ */
+public class WxConstants {
+
+    /**
+     * 默认编码
+     */
+    public static final String DEFAULT_CHARSET = "UTF-8";
+
+    /**
+     * 统一下单-扫描支付
+     */
+    public static String PAY_UNIFIEDORDER = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode";
+
+    public static String Test = "http://localhost:8088/HotWaters/userget_stu.action";
+
+    public static String Test2 = "http://localhost:8088/HotWaters/userstu_info.action";
+
+    /**
+     * 请求成功返回码
+     */
+    public final static String ERRCODE_OK_CODE = "0";
+    /**
+     * 错误的返回码的Key
+     */
+    public final static String ERRCODE = "errcode";
+
+    /**
+     * 返回状态码
+     */
+    public final static String RETURN_CODE= "return_code";
+
+    /**
+     * access_token 字符串
+     */
+    public final static String ACCESS_TOKEN = "access_token";
+
+    /**
+     * 签名类型 MD5
+     */
+    public final static String SING_MD5 = "MD5";
+
+    /**
+     * 签名类型 HMAC-SHA256
+     */
+    public final static String SING_HMACSHA256 = "HMAC-SHA256";
+
+}

+ 385 - 385
src/main/java/com/template/common/utils/WxUtil.java

@@ -1,385 +1,385 @@
-package com.template.common.utils;
-
-
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.crypto.Mac;
-import javax.crypto.spec.SecretKeySpec;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import java.io.*;
-import java.security.MessageDigest;
-import java.text.SimpleDateFormat;
-import java.util.*;
-
-/**
- * 微信公众号接口工具类
- * @author lujunjie
- * @date   2018/03/01
- */
-public class WxUtil {
-
-	/**
-	 * 加密/校验流程如下:
-	 * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
-	 * 2. 将三个参数字符串拼接成一个字符串进行sha1加密<br>
-	 * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信<br>
-	 *
-	 * @param token Token验证密钥
-	 * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数,nonce参数
-	 * @param timestamp 时间戳
-	 * @param nonce 随机数
-	 * @return 验证成功返回:true,失败返回:false
-	 */
-	public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
-		List<String> params = new ArrayList<String>();
-		params.add(token);
-		params.add(timestamp);
-		params.add(nonce);
-		//1. 将token、timestamp、nonce三个参数进行字典序排序
-		Collections.sort(params, new Comparator<String>() {
-			@Override
-			public int compare(String o1, String o2) {
-				return o1.compareTo(o2);
-			}
-		});
-		//2. 将三个参数字符串拼接成一个字符串进行sha1加密
-		String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
-		//3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
-		return temp.equals(signature);
-	}
-
-	/**
-	 * 输入流转化为字符串
-	 * @param inputStream 流
-	 * @return String 字符串
-	 * @throws Exception
-	 */
-	public static String getStreamString(InputStream inputStream) throws Exception{
-		StringBuffer buffer=new StringBuffer();
-		InputStreamReader inputStreamReader = null;
-		BufferedReader bufferedReader = null;
-		try{
-			inputStreamReader=new InputStreamReader(inputStream, WxConstants.DEFAULT_CHARSET);
-			bufferedReader=new BufferedReader(inputStreamReader);
-			String line;
-			while((line=bufferedReader.readLine())!=null){
-				buffer.append(line);
-			}
-		}catch(Exception e){
-			throw new Exception();
-		}finally {
-			if(bufferedReader != null){
-				bufferedReader.close();
-			}
-			if(inputStreamReader != null){
-				inputStreamReader.close();
-			}
-			if(inputStream != null){
-				inputStream.close();
-			}
-		}
-		return buffer.toString();
-	}
-
-	/**
-	 * 获取随机字符串 Nonce Str
-	 * @return String 随机字符串
-	 */
-	public static String getNonceStr() {
-		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
-	}
-
-	/**
-	 * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
-	 * @param data 待签名数据
-	 * @param apikey API密钥
-	 * @return 签名
-	 */
-	public static String getSignature(final Map<String, String> data, String apikey,
-				String signType) throws Exception {
-		Set<String> keySet = data.keySet();
-		String[] keyArray = keySet.toArray(new String[keySet.size()]);
-		Arrays.sort(keyArray);
-		StringBuilder sb = new StringBuilder();
-		sb.append(apikey);
-		sb.append("amount10apicodeCS0001collect_code");
-		sb.append(data.get("collect_code").trim());
-		sb.append("order_no");
-		sb.append(data.get("order_no").trim());
-        sb.append("timestamp");
-        sb.append(data.get("timestamp").trim());
-        sb.append(apikey);
-		System.out.println(sb);
-		if (signType.equals(WxConstants.SING_MD5)) {
-			System.out.println(MD5(sb.toString()).toUpperCase());
-			return MD5(sb.toString()).toLowerCase();
-		}
-		else if (signType.equals(WxConstants.SING_HMACSHA256)) {
-			return HMACSHA256(sb.toString(), apikey);
-		}
-		else {
-			throw new Exception(String.format("Invalid sign_type: %s", signType));
-		}
-	}
-
-	/**
-	 * 生成 MD5
-	 * @param data 待处理数据
-	 * @return MD5结果
-	 */
-	public static String MD5(String data) throws Exception {
-		MessageDigest md = MessageDigest.getInstance("MD5");
-		byte[] array = md.digest(data.getBytes("UTF-8"));
-		StringBuilder sb = new StringBuilder();
-		for (byte item : array) {
-			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
-		}
-		return sb.toString().toUpperCase();
-	}
-
-	/**
-	 * 生成 HMACSHA256
-	 * @param data 待处理数据
-	 * @param key 密钥
-	 * @return 加密结果
-	 * @throws Exception
-	 */
-	public static String HMACSHA256(String data, String key) throws Exception {
-		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
-		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
-		sha256_HMAC.init(secret_key);
-		byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
-		StringBuilder sb = new StringBuilder();
-		for (byte item : array) {
-			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
-		}
-		return sb.toString().toUpperCase();
-	}
-
-	/**
-	 * @param data Map类型数据
-	 * @return XML格式的字符串
-	 * @throws Exception
-	 */
-	public static String mapToXml(Map<String, String> data) throws Exception {
-		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
-		DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
-		org.w3c.dom.Document document = documentBuilder.newDocument();
-		org.w3c.dom.Element root = document.createElement("xml");
-		document.appendChild(root);
-		for (String key: data.keySet()) {
-			String value = data.get(key);
-			if (value == null) {
-				value = "";
-			}
-			value = value.trim();
-			org.w3c.dom.Element filed = document.createElement(key);
-			filed.appendChild(document.createTextNode(value));
-			root.appendChild(filed);
-		}
-		TransformerFactory tf = TransformerFactory.newInstance();
-		Transformer transformer = tf.newTransformer();
-		DOMSource source = new DOMSource(document);
-		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-		StringWriter writer = new StringWriter();
-		StreamResult result = new StreamResult(writer);
-		transformer.transform(source, result);
-		String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
-		try {
-			writer.close();
-		}
-		catch (Exception ex) {
-		}
-		return output;
-	}
-
-	/**
-	 * 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
-	 * @param xmlStr API返回的XML格式数据
-	 * @return Map类型数据
-	 * @throws Exception
-	 */
-	public static Map<String, String> processResponseXml(String xmlStr,String signType) throws Exception {
-		String RETURN_CODE = WxConstants.RETURN_CODE;
-		String return_code;
-		Map<String, String> respData = xmlToMap(xmlStr);
-		if (respData.containsKey(RETURN_CODE)) {
-			return_code = respData.get(RETURN_CODE);
-		}
-		else {
-			throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
-		}
-
-		if (return_code.equals("FAIL")) {
-			return respData;
-		}
-		else if (return_code.equals("SUCCESS")) {
-			if (isResponseSignatureValid(respData,signType)) {
-				return respData;
-			}
-			else {
-				throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
-			}
-		}
-		else {
-			throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
-		}
-	}
-
-
-	/**
-	 * XML格式字符串转换为Map
-	 * @param strXML XML字符串
-	 * @return XML数据转换后的Map
-	 * @throws Exception
-	 */
-	public static Map<String, String> xmlToMap(String strXML) throws Exception {
-		try {
-			Map<String, String> data = new HashMap<String, String>();
-			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
-
-			String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
-			documentBuilderFactory.setFeature(FEATURE, true);
-
-			FEATURE = "http://xml.org/sax/features/external-general-entities";
-			documentBuilderFactory.setFeature(FEATURE, false);
-
-			FEATURE = "http://xml.org/sax/features/external-parameter-entities";
-			documentBuilderFactory.setFeature(FEATURE, false);
-
-			FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
-			documentBuilderFactory.setFeature(FEATURE, false);
-
-			documentBuilderFactory.setXIncludeAware(false);
-			documentBuilderFactory.setExpandEntityReferences(false);
-			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
-			InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
-			org.w3c.dom.Document doc = documentBuilder.parse(stream);
-			doc.getDocumentElement().normalize();
-			NodeList nodeList = doc.getDocumentElement().getChildNodes();
-			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
-				Node node = nodeList.item(idx);
-				if (node.getNodeType() == Node.ELEMENT_NODE) {
-					org.w3c.dom.Element element = (org.w3c.dom.Element) node;
-					data.put(element.getNodeName(), element.getTextContent());
-				}
-			}
-			try {
-				stream.close();
-			} catch (Exception ex) {
-				// do nothing
-			}
-			return data;
-		} catch (Exception ex) {
-			throw ex;
-		}
-	}
-
-	/**
-	 * 判断xml数据的sign是否有效,必须包含sign字段,否则返回false。
-	 * @param reqData 向wxpay post的请求数据
-	 * @return 签名是否有效
-	 * @throws Exception
-	 */
-	private static boolean isResponseSignatureValid(final Map<String, String> reqData,String signType) throws Exception {
-		// 返回数据的签名方式和请求中给定的签名方式是一致的
-		return isSignatureValid(reqData,WxConfig.apikey,signType);
-	}
-
-	/**
-	 * 判断签名是否正确,必须包含sign字段,否则返回false。
-	 * @param data Map类型数据
-	 * @param key API密钥
-	 * @param signType 签名方式
-	 * @return 签名是否正确
-	 * @throws Exception
-	 */
-	public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
-		if (!data.containsKey("sign")) {
-			return false;
-		}
-		String sign = data.get("sign");
-		return getSignature(data, key, signType).equals(sign);
-	}
-
-//	/**
-//	 * 生成支付二维码
-//	 * @param response 响应
-//	 * @param contents url链接
-//	 * @throws Exception
-//	 */
-//	public static void writerPayImage(HttpServletResponse response, String contents) throws Exception{
-//		ServletOutputStream out = response.getOutputStream();
-//		try {
-//			Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
-//			hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
-//			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
-//			hints.put(EncodeHintType.MARGIN, 0);
-//			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,300,300,hints);
-//			MatrixToImageWriter.writeToStream(bitMatrix,"jpg",out);
-//		}catch (Exception e){
-//			throw new Exception("生成二维码失败!");
-//		}finally {
-//			if(out != null){
-//				out.flush();
-//				out.close();
-//			}
-//		}
-//	}
-
-	/**
-	 * 生成商户订单号
-	 * @return String
-	 */
-	public static String mchOrderNo(){
-		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
-		String date = sdf.format(new Date());
-
-		Random random = new Random();
-		String fourRandom = String.valueOf(random.nextInt(10000));
-		int randLength = fourRandom.length();
-		//不足4位继续补充
-		if(randLength<4){
-			for(int remain = 1; remain <= 4 - randLength; remain ++ ){
-				fourRandom += random.nextInt(10)  ;
-			}
-		}
-		return date+fourRandom;
-	}
-
-	/**
-	 * 生成默认用户名
-	 * @return String
-	 */
-	public static String createDefaultUserName(){
-		SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmss");
-		String date = sdf.format(new Date());
-		return "微信用户" + date;
-	}
-
-	/**
-	 * 返回信息给微信
-	 * @param response
-	 * @param content 内容
-	 * @throws Exception
-	 */
-	public static void responsePrint(HttpServletResponse response, String content) throws Exception{
-		response.setCharacterEncoding("UTF-8");
-		response.setContentType("text/xml");
-		response.getWriter().print(content);
-		response.getWriter().flush();
-		response.getWriter().close();
-	}
-
-
-}
+package com.template.common.utils;
+
+
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.*;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * 微信公众号接口工具类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class WxUtil {
+
+	/**
+	 * 加密/校验流程如下:
+	 * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
+	 * 2. 将三个参数字符串拼接成一个字符串进行sha1加密<br>
+	 * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信<br>
+	 *
+	 * @param token Token验证密钥
+	 * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数,nonce参数
+	 * @param timestamp 时间戳
+	 * @param nonce 随机数
+	 * @return 验证成功返回:true,失败返回:false
+	 */
+	public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
+		List<String> params = new ArrayList<String>();
+		params.add(token);
+		params.add(timestamp);
+		params.add(nonce);
+		//1. 将token、timestamp、nonce三个参数进行字典序排序
+		Collections.sort(params, new Comparator<String>() {
+			@Override
+			public int compare(String o1, String o2) {
+				return o1.compareTo(o2);
+			}
+		});
+		//2. 将三个参数字符串拼接成一个字符串进行sha1加密
+		String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
+		//3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
+		return temp.equals(signature);
+	}
+
+	/**
+	 * 输入流转化为字符串
+	 * @param inputStream 流
+	 * @return String 字符串
+	 * @throws Exception
+	 */
+	public static String getStreamString(InputStream inputStream) throws Exception{
+		StringBuffer buffer=new StringBuffer();
+		InputStreamReader inputStreamReader = null;
+		BufferedReader bufferedReader = null;
+		try{
+			inputStreamReader=new InputStreamReader(inputStream, WxConstants.DEFAULT_CHARSET);
+			bufferedReader=new BufferedReader(inputStreamReader);
+			String line;
+			while((line=bufferedReader.readLine())!=null){
+				buffer.append(line);
+			}
+		}catch(Exception e){
+			throw new Exception();
+		}finally {
+			if(bufferedReader != null){
+				bufferedReader.close();
+			}
+			if(inputStreamReader != null){
+				inputStreamReader.close();
+			}
+			if(inputStream != null){
+				inputStream.close();
+			}
+		}
+		return buffer.toString();
+	}
+
+	/**
+	 * 获取随机字符串 Nonce Str
+	 * @return String 随机字符串
+	 */
+	public static String getNonceStr() {
+		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
+	}
+
+	/**
+	 * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
+	 * @param data 待签名数据
+	 * @param apikey API密钥
+	 * @return 签名
+	 */
+	public static String getSignature(final Map<String, String> data, String apikey,
+				String signType) throws Exception {
+		Set<String> keySet = data.keySet();
+		String[] keyArray = keySet.toArray(new String[keySet.size()]);
+		Arrays.sort(keyArray);
+		StringBuilder sb = new StringBuilder();
+		sb.append(apikey);
+		sb.append("amount10apicodeCS0001collect_code");
+		sb.append(data.get("collect_code").trim());
+		sb.append("order_no");
+		sb.append(data.get("order_no").trim());
+        sb.append("timestamp");
+        sb.append(data.get("timestamp").trim());
+        sb.append(apikey);
+		System.out.println(sb);
+		if (signType.equals(WxConstants.SING_MD5)) {
+			System.out.println(MD5(sb.toString()).toUpperCase());
+			return MD5(sb.toString()).toLowerCase();
+		}
+		else if (signType.equals(WxConstants.SING_HMACSHA256)) {
+			return HMACSHA256(sb.toString(), apikey);
+		}
+		else {
+			throw new Exception(String.format("Invalid sign_type: %s", signType));
+		}
+	}
+
+	/**
+	 * 生成 MD5
+	 * @param data 待处理数据
+	 * @return MD5结果
+	 */
+	public static String MD5(String data) throws Exception {
+		MessageDigest md = MessageDigest.getInstance("MD5");
+		byte[] array = md.digest(data.getBytes("UTF-8"));
+		StringBuilder sb = new StringBuilder();
+		for (byte item : array) {
+			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
+		}
+		return sb.toString().toUpperCase();
+	}
+
+	/**
+	 * 生成 HMACSHA256
+	 * @param data 待处理数据
+	 * @param key 密钥
+	 * @return 加密结果
+	 * @throws Exception
+	 */
+	public static String HMACSHA256(String data, String key) throws Exception {
+		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
+		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
+		sha256_HMAC.init(secret_key);
+		byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
+		StringBuilder sb = new StringBuilder();
+		for (byte item : array) {
+			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
+		}
+		return sb.toString().toUpperCase();
+	}
+
+	/**
+	 * @param data Map类型数据
+	 * @return XML格式的字符串
+	 * @throws Exception
+	 */
+	public static String mapToXml(Map<String, String> data) throws Exception {
+		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+		DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
+		org.w3c.dom.Document document = documentBuilder.newDocument();
+		org.w3c.dom.Element root = document.createElement("xml");
+		document.appendChild(root);
+		for (String key: data.keySet()) {
+			String value = data.get(key);
+			if (value == null) {
+				value = "";
+			}
+			value = value.trim();
+			org.w3c.dom.Element filed = document.createElement(key);
+			filed.appendChild(document.createTextNode(value));
+			root.appendChild(filed);
+		}
+		TransformerFactory tf = TransformerFactory.newInstance();
+		Transformer transformer = tf.newTransformer();
+		DOMSource source = new DOMSource(document);
+		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+		StringWriter writer = new StringWriter();
+		StreamResult result = new StreamResult(writer);
+		transformer.transform(source, result);
+		String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
+		try {
+			writer.close();
+		}
+		catch (Exception ex) {
+		}
+		return output;
+	}
+
+	/**
+	 * 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
+	 * @param xmlStr API返回的XML格式数据
+	 * @return Map类型数据
+	 * @throws Exception
+	 */
+	public static Map<String, String> processResponseXml(String xmlStr,String signType) throws Exception {
+		String RETURN_CODE = WxConstants.RETURN_CODE;
+		String return_code;
+		Map<String, String> respData = xmlToMap(xmlStr);
+		if (respData.containsKey(RETURN_CODE)) {
+			return_code = respData.get(RETURN_CODE);
+		}
+		else {
+			throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
+		}
+
+		if (return_code.equals("FAIL")) {
+			return respData;
+		}
+		else if (return_code.equals("SUCCESS")) {
+			if (isResponseSignatureValid(respData,signType)) {
+				return respData;
+			}
+			else {
+				throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
+			}
+		}
+		else {
+			throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
+		}
+	}
+
+
+	/**
+	 * XML格式字符串转换为Map
+	 * @param strXML XML字符串
+	 * @return XML数据转换后的Map
+	 * @throws Exception
+	 */
+	public static Map<String, String> xmlToMap(String strXML) throws Exception {
+		try {
+			Map<String, String> data = new HashMap<String, String>();
+			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+
+			String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
+			documentBuilderFactory.setFeature(FEATURE, true);
+
+			FEATURE = "http://xml.org/sax/features/external-general-entities";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			FEATURE = "http://xml.org/sax/features/external-parameter-entities";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			documentBuilderFactory.setXIncludeAware(false);
+			documentBuilderFactory.setExpandEntityReferences(false);
+			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+			InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
+			org.w3c.dom.Document doc = documentBuilder.parse(stream);
+			doc.getDocumentElement().normalize();
+			NodeList nodeList = doc.getDocumentElement().getChildNodes();
+			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
+				Node node = nodeList.item(idx);
+				if (node.getNodeType() == Node.ELEMENT_NODE) {
+					org.w3c.dom.Element element = (org.w3c.dom.Element) node;
+					data.put(element.getNodeName(), element.getTextContent());
+				}
+			}
+			try {
+				stream.close();
+			} catch (Exception ex) {
+				// do nothing
+			}
+			return data;
+		} catch (Exception ex) {
+			throw ex;
+		}
+	}
+
+	/**
+	 * 判断xml数据的sign是否有效,必须包含sign字段,否则返回false。
+	 * @param reqData 向wxpay post的请求数据
+	 * @return 签名是否有效
+	 * @throws Exception
+	 */
+	private static boolean isResponseSignatureValid(final Map<String, String> reqData,String signType) throws Exception {
+		// 返回数据的签名方式和请求中给定的签名方式是一致的
+		return isSignatureValid(reqData,WxConfig.apikey,signType);
+	}
+
+	/**
+	 * 判断签名是否正确,必须包含sign字段,否则返回false。
+	 * @param data Map类型数据
+	 * @param key API密钥
+	 * @param signType 签名方式
+	 * @return 签名是否正确
+	 * @throws Exception
+	 */
+	public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
+		if (!data.containsKey("sign")) {
+			return false;
+		}
+		String sign = data.get("sign");
+		return getSignature(data, key, signType).equals(sign);
+	}
+
+//	/**
+//	 * 生成支付二维码
+//	 * @param response 响应
+//	 * @param contents url链接
+//	 * @throws Exception
+//	 */
+//	public static void writerPayImage(HttpServletResponse response, String contents) throws Exception{
+//		ServletOutputStream out = response.getOutputStream();
+//		try {
+//			Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
+//			hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
+//			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
+//			hints.put(EncodeHintType.MARGIN, 0);
+//			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,300,300,hints);
+//			MatrixToImageWriter.writeToStream(bitMatrix,"jpg",out);
+//		}catch (Exception e){
+//			throw new Exception("生成二维码失败!");
+//		}finally {
+//			if(out != null){
+//				out.flush();
+//				out.close();
+//			}
+//		}
+//	}
+
+	/**
+	 * 生成商户订单号
+	 * @return String
+	 */
+	public static String mchOrderNo(){
+		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
+		String date = sdf.format(new Date());
+
+		Random random = new Random();
+		String fourRandom = String.valueOf(random.nextInt(10000));
+		int randLength = fourRandom.length();
+		//不足4位继续补充
+		if(randLength<4){
+			for(int remain = 1; remain <= 4 - randLength; remain ++ ){
+				fourRandom += random.nextInt(10)  ;
+			}
+		}
+		return date+fourRandom;
+	}
+
+	/**
+	 * 生成默认用户名
+	 * @return String
+	 */
+	public static String createDefaultUserName(){
+		SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmss");
+		String date = sdf.format(new Date());
+		return "微信用户" + date;
+	}
+
+	/**
+	 * 返回信息给微信
+	 * @param response
+	 * @param content 内容
+	 * @throws Exception
+	 */
+	public static void responsePrint(HttpServletResponse response, String content) throws Exception{
+		response.setCharacterEncoding("UTF-8");
+		response.setContentType("text/xml");
+		response.getWriter().print(content);
+		response.getWriter().flush();
+		response.getWriter().close();
+	}
+
+
+}

+ 47 - 47
src/main/java/com/template/common/utils/imageUtils.java

@@ -1,47 +1,47 @@
-package com.template.common.utils;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.Base64;
-
-/**
- * @Author: binguo
- * @Date: 2024/1/9 星期二 15:17
- * @Description: com.template.common.utils
- * @Version: 1.0
- */
-public class imageUtils {
-
-    public static String getBase64Url(String imagePath){
-        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
-        byte[] data = new byte[1024];
-        try {
-            // 创建URL
-            URL url = new URL(imagePath);
-            // 创建链接
-            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-            conn.setRequestMethod("GET");
-            conn.setConnectTimeout(10 * 1000);
-
-            if(conn.getResponseCode() != 200) {
-                return "fail";//连接失败/链接失效/图片不存在
-            }
-            InputStream inStream = conn.getInputStream();
-            int len = -1;
-            while ((len = inStream.read(data)) != -1) {
-                outPut.write(data, 0, len);
-            }
-            inStream.close();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        // 对字节数组Base64编码
-        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
-        String res = new String(encode);
-        return res;
-    }
-    //https://www.jb51.net/program/288342ppk.htm 图片压缩大小
-}
+package com.template.common.utils;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Base64;
+
+/**
+ * @Author: binguo
+ * @Date: 2024/1/9 星期二 15:17
+ * @Description: com.template.common.utils
+ * @Version: 1.0
+ */
+public class imageUtils {
+
+    public static String getBase64Url(String imagePath){
+        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
+        byte[] data = new byte[1024];
+        try {
+            // 创建URL
+            URL url = new URL(imagePath);
+            // 创建链接
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            conn.setRequestMethod("GET");
+            conn.setConnectTimeout(10 * 1000);
+
+            if(conn.getResponseCode() != 200) {
+                return "fail";//连接失败/链接失效/图片不存在
+            }
+            InputStream inStream = conn.getInputStream();
+            int len = -1;
+            while ((len = inStream.read(data)) != -1) {
+                outPut.write(data, 0, len);
+            }
+            inStream.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        // 对字节数组Base64编码
+        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
+        String res = new String(encode);
+        return res;
+    }
+    //https://www.jb51.net/program/288342ppk.htm 图片压缩大小
+}

+ 27 - 27
src/main/java/com/template/common/utils/paramUtils.java

@@ -1,27 +1,27 @@
-package com.template.common.utils;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.validation.BindingResult;
-import org.springframework.validation.ObjectError;
-
-import java.util.List;
-
-/**
- * @Author: binguo
- * @Date: 2023/7/5 星期三 16:11
- * @Description: com.template.utils
- * @Version: 1.0
- */
-@Slf4j
-public class paramUtils {
-    public static String getParamError(BindingResult bindingResult){
-        //有校验没通过
-        List<ObjectError> errorList = bindingResult.getAllErrors();
-        StringBuilder st = new StringBuilder();
-        for (ObjectError error : errorList) {
-            st.append(error.getDefaultMessage()+"! ");//输出具体的错误信息
-        }
-
-        return st.toString();
-    }
-}
+package com.template.common.utils;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.ObjectError;
+
+import java.util.List;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/7/5 星期三 16:11
+ * @Description: com.template.utils
+ * @Version: 1.0
+ */
+@Slf4j
+public class paramUtils {
+    public static String getParamError(BindingResult bindingResult){
+        //有校验没通过
+        List<ObjectError> errorList = bindingResult.getAllErrors();
+        StringBuilder st = new StringBuilder();
+        for (ObjectError error : errorList) {
+            st.append(error.getDefaultMessage()+"! ");//输出具体的错误信息
+        }
+
+        return st.toString();
+    }
+}

+ 25 - 25
src/main/java/com/template/common/utils/smsUtil.java

@@ -1,25 +1,25 @@
-package com.template.common.utils;
-
-/**
- * @Author: binguo
- * @Date: 2023/4/20 星期四 8:26
- * @Description: common
- * @Version: 1.0
- */
-public class smsUtil {
-//    @Autowired
-//    private static smsConfig smsConfig;
-//
-//    /**
-//     * 发送单条短信验证码
-//     * @param smmCode 短信验证码
-//     * @param phoneNumber 手机号
-//     * @return
-//     */
-//    public static void sendSingleMessage(String smmCode, String phoneNumber) throws HTTPException, IOException {
-//        String[] params = {smmCode,Integer.toString(smsConfig.getSmsMin())};
-//        SmsSingleSender ssender = new SmsSingleSender(smsConfig.getSdkAppid(), smsConfig.getAppKey());
-//        SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber, smsConfig.getTemplateId(), params, smsConfig.getSmsSign(), "", "");
-//        System.out.println(result);
-//    };
-}
+package com.template.common.utils;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/4/20 星期四 8:26
+ * @Description: common
+ * @Version: 1.0
+ */
+public class smsUtil {
+//    @Autowired
+//    private static smsConfig smsConfig;
+//
+//    /**
+//     * 发送单条短信验证码
+//     * @param smmCode 短信验证码
+//     * @param phoneNumber 手机号
+//     * @return
+//     */
+//    public static void sendSingleMessage(String smmCode, String phoneNumber) throws HTTPException, IOException {
+//        String[] params = {smmCode,Integer.toString(smsConfig.getSmsMin())};
+//        SmsSingleSender ssender = new SmsSingleSender(smsConfig.getSdkAppid(), smsConfig.getAppKey());
+//        SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber, smsConfig.getTemplateId(), params, smsConfig.getSmsSign(), "", "");
+//        System.out.println(result);
+//    };
+}

+ 53 - 53
src/main/java/com/template/config/CosConfig.java

@@ -1,53 +1,53 @@
-package com.template.config;
-
-import com.qcloud.cos.COSClient;
-import com.qcloud.cos.ClientConfig;
-import com.qcloud.cos.auth.BasicCOSCredentials;
-import com.qcloud.cos.auth.COSCredentials;
-import com.qcloud.cos.region.Region;
-import lombok.Data;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Bean;
-import org.springframework.stereotype.Component;
-
-@Component
-@ConfigurationProperties(prefix = "cos")
-@Data
-public class CosConfig {
-    /**
-     * 腾讯云账号秘钥
-     */
-    private String secretId;
-    /**
-     * 密码秘钥
-     */
-    private String secretKey;
-    /**
-     * 存储桶地区
-     */
-    private String region;
-    /**
-     * 存储桶名称
-     */
-    private String bucketName;
-    /**
-     * 存储桶访问路径
-     */
-    private String path;
-
-    /**
-     * 初始化cos对象,配置相关配置信息
-     */
-    @Bean
-    public COSClient cosClient(){
-        // 1 初始化用户身份信息(secretId, secretKey)。
-        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
-        // 2 设置 bucket 的区域
-        Region region = new Region(this.region);
-        ClientConfig clientConfig = new ClientConfig(region);
-        // 3 生成 cos 客户端。
-        COSClient cosClient = new COSClient(cred, clientConfig);
-        return cosClient;
-    }
-}
-
+package com.template.config;
+
+import com.qcloud.cos.COSClient;
+import com.qcloud.cos.ClientConfig;
+import com.qcloud.cos.auth.BasicCOSCredentials;
+import com.qcloud.cos.auth.COSCredentials;
+import com.qcloud.cos.region.Region;
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.stereotype.Component;
+
+@Component
+@ConfigurationProperties(prefix = "cos")
+@Data
+public class CosConfig {
+    /**
+     * 腾讯云账号秘钥
+     */
+    private String secretId;
+    /**
+     * 密码秘钥
+     */
+    private String secretKey;
+    /**
+     * 存储桶地区
+     */
+    private String region;
+    /**
+     * 存储桶名称
+     */
+    private String bucketName;
+    /**
+     * 存储桶访问路径
+     */
+    private String path;
+
+    /**
+     * 初始化cos对象,配置相关配置信息
+     */
+    @Bean
+    public COSClient cosClient(){
+        // 1 初始化用户身份信息(secretId, secretKey)。
+        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
+        // 2 设置 bucket 的区域
+        Region region = new Region(this.region);
+        ClientConfig clientConfig = new ClientConfig(region);
+        // 3 生成 cos 客户端。
+        COSClient cosClient = new COSClient(cred, clientConfig);
+        return cosClient;
+    }
+}
+

+ 52 - 52
src/main/java/com/template/config/MyBatisPlusConfig.java

@@ -1,52 +1,52 @@
-package com.template.config;
-
-import com.baomidou.mybatisplus.core.injector.ISqlInjector;
-import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
-import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
-import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
-import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
-import org.mybatis.spring.annotation.MapperScan;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-// 扫描我们的 mapper 文件夹
-@MapperScan("com.template.mapper")
-@EnableTransactionManagement
-@Configuration // 配置类
-public class MyBatisPlusConfig {
-
-    // 注册乐观锁插件
-    @Bean
-    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
-        return new OptimisticLockerInterceptor();
-    }
-
-    // 分页插件
-    @Bean
-    public PaginationInterceptor paginationInterceptor() {
-        return  new PaginationInterceptor();
-    }
-
-    // 逻辑删除组件!
-    @Bean
-    public ISqlInjector sqlInjector() {
-        return new LogicSqlInjector();
-    }
-
-
-    /**
-     * SQL执行效率插件
-     * 在控制台显示sql语句
-     */
-    @Bean
-    @Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
-    public PerformanceInterceptor performanceInterceptor() {
-        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
-        performanceInterceptor.setMaxTime(3000); //ms 设置sql执行的最大时间,如果超过了则不执行
-        performanceInterceptor.setFormat(true);
-        return performanceInterceptor;
-    }
-
-}
+package com.template.config;
+
+import com.baomidou.mybatisplus.core.injector.ISqlInjector;
+import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
+import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
+import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
+import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+// 扫描我们的 mapper 文件夹
+@MapperScan("com.template.mapper")
+@EnableTransactionManagement
+@Configuration // 配置类
+public class MyBatisPlusConfig {
+
+    // 注册乐观锁插件
+    @Bean
+    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
+        return new OptimisticLockerInterceptor();
+    }
+
+    // 分页插件
+    @Bean
+    public PaginationInterceptor paginationInterceptor() {
+        return  new PaginationInterceptor();
+    }
+
+    // 逻辑删除组件!
+    @Bean
+    public ISqlInjector sqlInjector() {
+        return new LogicSqlInjector();
+    }
+
+
+    /**
+     * SQL执行效率插件
+     * 在控制台显示sql语句
+     */
+    @Bean
+    @Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
+    public PerformanceInterceptor performanceInterceptor() {
+        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
+        performanceInterceptor.setMaxTime(3000); //ms 设置sql执行的最大时间,如果超过了则不执行
+        performanceInterceptor.setFormat(true);
+        return performanceInterceptor;
+    }
+
+}

+ 37 - 37
src/main/java/com/template/config/MySecurity.java

@@ -1,37 +1,37 @@
-package com.template.config;
-
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-@Component
-//@ConfigurationProperties(prefix = "my-security")
-public class MySecurity {
-    @Value("${my-security.privateKey}")
-    public String privateKey;
-    @Value("${my-security.publicKey}")
-    public String publicKey;
-
-    public String getPrivateKey() {
-        return privateKey;
-    }
-
-    public String getPublicKey() {
-        return publicKey;
-    }
-
-    @Override
-    public String toString() {
-        return "MySecurity{" +
-                "privateKey='" + privateKey + '\'' +
-                ", publicKey='" + publicKey + '\'' +
-                '}';
-    }
-
-    public void setPrivateKey(String privateKey) {
-        this.privateKey = privateKey;
-    }
-
-    public void setPublicKey(String publicKey) {
-        this.publicKey = publicKey;
-    }
-}
+package com.template.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+@Component
+//@ConfigurationProperties(prefix = "my-security")
+public class MySecurity {
+    @Value("${my-security.privateKey}")
+    public String privateKey;
+    @Value("${my-security.publicKey}")
+    public String publicKey;
+
+    public String getPrivateKey() {
+        return privateKey;
+    }
+
+    public String getPublicKey() {
+        return publicKey;
+    }
+
+    @Override
+    public String toString() {
+        return "MySecurity{" +
+                "privateKey='" + privateKey + '\'' +
+                ", publicKey='" + publicKey + '\'' +
+                '}';
+    }
+
+    public void setPrivateKey(String privateKey) {
+        this.privateKey = privateKey;
+    }
+
+    public void setPublicKey(String publicKey) {
+        this.publicKey = publicKey;
+    }
+}

+ 36 - 36
src/main/java/com/template/config/smsConfig.java

@@ -1,36 +1,36 @@
-package com.template.config;
-
-import lombok.Data;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.stereotype.Component;
-
-/**
- * @Author: binguo
- * @Date: 2023/4/20 星期四 8:29
- * @Description: com.video.config
- * @Version: 1.0
- */
-
-@Component
-@ConfigurationProperties(prefix = "tencentcloud")
-@Data
-public class smsConfig {
-
-    //腾讯云上的签名  AKIDCPVZdcWIxgHpy5FYxVyPiqkZGrhdXUBg
-    private String secretID;
-
-    //腾讯云上的密钥   NkyCN3cz97qKaeXLvHOGxOcdS8f184pL
-    private String secretKey;
-
-    //短信应用id  1400885930
-    private String sdkAppid;
-
-    //短信签名内容  	江西省创海科技有限公司
-    private String signName;
-
-    //模板Id   2060673
-    private String templateId;
-
-    //验证码有效时长
-    private String smsMin;
-}
+package com.template.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/4/20 星期四 8:29
+ * @Description: com.video.config
+ * @Version: 1.0
+ */
+
+@Component
+@ConfigurationProperties(prefix = "tencentcloud")
+@Data
+public class smsConfig {
+
+    //腾讯云上的签名  AKIDCPVZdcWIxgHpy5FYxVyPiqkZGrhdXUBg
+    private String secretID;
+
+    //腾讯云上的密钥   NkyCN3cz97qKaeXLvHOGxOcdS8f184pL
+    private String secretKey;
+
+    //短信应用id  1400885930
+    private String sdkAppid;
+
+    //短信签名内容  	江西省创海科技有限公司
+    private String signName;
+
+    //模板Id   2060673
+    private String templateId;
+
+    //验证码有效时长
+    private String smsMin;
+}

+ 111 - 111
src/main/java/com/template/controller/BookingController.java

@@ -1,111 +1,111 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.BookingControllerAPI;
-import com.template.api.SystemMenuControllerAPI;
-import com.template.mapper.BookingMapper;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import com.template.services.SystemMenuService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class BookingController implements BookingControllerAPI {
-
-    @Autowired
-    private BookingMapper bookingMapper;
-
-    @Override
-    @PassToken
-    public CommonResult QueryBookingTotal() {
-        Map<String,Object> result=new HashMap<>();
-        List<Map<String, String>> yestedayTotal = bookingMapper.getYestedayTotal();
-        List<Map<String, String>> total = bookingMapper.getTotal();
-        try {
-            result.put("count",total.get(0).get("count"));
-            result.put("value",total.get(0).get("value")==null?0:total.get(0).get("value"));
-            result.put("yestedayCount",yestedayTotal.get(0).get("count"));
-            result.put("yestedayValue",yestedayTotal.get(0).get("value")==null?0:yestedayTotal.get(0).get("value"));
-        } catch (Exception e) {
-            e.printStackTrace();
-            return CommonResult.fail(e.getMessage());
-        }
-        return CommonResult.ok(result);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult QueryBookingTrend() {
-        List<Map<String, String>> trendList = bookingMapper.get7Trend();
-        if(trendList==null||trendList.size()==0){
-            return CommonResult.ok(trendList);
-        }
-        return CommonResult.ok(trendList);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult QueryBookingAvgPrice() {
-        List<Map<String, String>> avgList = bookingMapper.get7Avg();
-        if(avgList==null||avgList.size()==0){
-            return CommonResult.ok(avgList);
-        }
-        return CommonResult.ok(avgList);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult QueryOrderRank() {
-        List<Map<String, String>> avgList = bookingMapper.getRank();
-        if(avgList==null||avgList.size()==0){
-            return CommonResult.ok(avgList);
-        }
-        return CommonResult.ok(avgList);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getCommentAvg() {
-        List<Map<String, String>> avgList = bookingMapper.getCommentAvg();
-        if(avgList==null||avgList.size()==0){
-            return CommonResult.ok(avgList);
-        }
-        return CommonResult.ok(avgList);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getCommentInfo(String name,String startTime,String endTime,String flag,int pageNum,int pageSize) {
-        int pageIndex=pageNum==1?0:(pageNum-1)*pageSize;
-        List<Map<String, String>> commentInfo = bookingMapper.getCommentInfo(name,startTime,endTime,flag,pageIndex,pageSize);
-        if(commentInfo==null||commentInfo.size()==0){
-            return CommonResult.ok(commentInfo);
-        }
-        int total=bookingMapper.getCommentInfoTotal(name,startTime,endTime,flag);
-        Map<String, Object> resultMap=new HashMap<>();
-        resultMap.put("total",total);
-        resultMap.put("commentInfoList",commentInfo);
-        return CommonResult.ok(resultMap);
-    }
-
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.BookingControllerAPI;
+import com.template.api.SystemMenuControllerAPI;
+import com.template.mapper.BookingMapper;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import com.template.services.SystemMenuService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class BookingController implements BookingControllerAPI {
+
+    @Autowired
+    private BookingMapper bookingMapper;
+
+    @Override
+    @PassToken
+    public CommonResult QueryBookingTotal() {
+        Map<String,Object> result=new HashMap<>();
+        List<Map<String, String>> yestedayTotal = bookingMapper.getYestedayTotal();
+        List<Map<String, String>> total = bookingMapper.getTotal();
+        try {
+            result.put("count",total.get(0).get("count"));
+            result.put("value",total.get(0).get("value")==null?0:total.get(0).get("value"));
+            result.put("yestedayCount",yestedayTotal.get(0).get("count"));
+            result.put("yestedayValue",yestedayTotal.get(0).get("value")==null?0:yestedayTotal.get(0).get("value"));
+        } catch (Exception e) {
+            e.printStackTrace();
+            return CommonResult.fail(e.getMessage());
+        }
+        return CommonResult.ok(result);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult QueryBookingTrend() {
+        List<Map<String, String>> trendList = bookingMapper.get7Trend();
+        if(trendList==null||trendList.size()==0){
+            return CommonResult.ok(trendList);
+        }
+        return CommonResult.ok(trendList);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult QueryBookingAvgPrice() {
+        List<Map<String, String>> avgList = bookingMapper.get7Avg();
+        if(avgList==null||avgList.size()==0){
+            return CommonResult.ok(avgList);
+        }
+        return CommonResult.ok(avgList);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult QueryOrderRank() {
+        List<Map<String, String>> avgList = bookingMapper.getRank();
+        if(avgList==null||avgList.size()==0){
+            return CommonResult.ok(avgList);
+        }
+        return CommonResult.ok(avgList);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getCommentAvg() {
+        List<Map<String, String>> avgList = bookingMapper.getCommentAvg();
+        if(avgList==null||avgList.size()==0){
+            return CommonResult.ok(avgList);
+        }
+        return CommonResult.ok(avgList);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getCommentInfo(String name,String startTime,String endTime,String flag,int pageNum,int pageSize) {
+        int pageIndex=pageNum==1?0:(pageNum-1)*pageSize;
+        List<Map<String, String>> commentInfo = bookingMapper.getCommentInfo(name,startTime,endTime,flag,pageIndex,pageSize);
+        if(commentInfo==null||commentInfo.size()==0){
+            return CommonResult.ok(commentInfo);
+        }
+        int total=bookingMapper.getCommentInfoTotal(name,startTime,endTime,flag);
+        Map<String, Object> resultMap=new HashMap<>();
+        resultMap.put("total",total);
+        resultMap.put("commentInfoList",commentInfo);
+        return CommonResult.ok(resultMap);
+    }
+
+}
+

+ 46 - 46
src/main/java/com/template/controller/CateringController.java

@@ -1,46 +1,46 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.CateringControllerAPI;
-import com.template.api.SystemMenuControllerAPI;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import com.template.services.SystemMenuService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class CateringController implements CateringControllerAPI {
-
-
-    @Override
-    @PassToken
-    public CommonResult getTotal() {
-        Map<String,String> result=new HashMap<>();
-        result.put("中餐","221");
-        result.put("西餐","105");
-        result.put("小吃","150");
-        result.put("小卖部","65");
-        result.put("其他","88");
-        return CommonResult.ok(result);
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.CateringControllerAPI;
+import com.template.api.SystemMenuControllerAPI;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import com.template.services.SystemMenuService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class CateringController implements CateringControllerAPI {
+
+
+    @Override
+    @PassToken
+    public CommonResult getTotal() {
+        Map<String,String> result=new HashMap<>();
+        result.put("中餐","221");
+        result.put("西餐","105");
+        result.put("小吃","150");
+        result.put("小卖部","65");
+        result.put("其他","88");
+        return CommonResult.ok(result);
+    }
+}
+

+ 89 - 89
src/main/java/com/template/controller/ExcelController.java

@@ -1,89 +1,89 @@
-package com.template.controller;
-
-import com.template.annotation.PassToken;
-import com.template.api.ExcelControllerAPI;
-import com.template.model.pojo.SystemUser;
-import com.template.services.SystemUserService;
-import org.apache.poi.ss.usermodel.DataFormatter;
-import org.apache.poi.xssf.usermodel.XSSFCell;
-import org.apache.poi.xssf.usermodel.XSSFSheet;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-
-@RestController
-public class ExcelController implements ExcelControllerAPI {
-    @Autowired
-    SystemUserService systemUserService;
-
-    /**
-     * .xlsx格式
-     * @param
-     */
-    @Override
-    @PassToken
-    public void toExcel(String fileUrl) {
-        //创建工作簿对象
-        XSSFWorkbook xssfWorkbook = null;
-        try {
-            xssfWorkbook = new XSSFWorkbook(new FileInputStream(fileUrl));
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-        //获取工作簿下sheet的个数
-        int sheetNum = xssfWorkbook.getNumberOfSheets();
-        //遍历工作簿中的所有数据
-        for (int i = 0; i < sheetNum; i++) {
-            //读取第i个工作表
-            System.out.println("读取第"+(i+1)+"个sheet");
-            XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
-            //获取最后一行的num,即总行数。此处从0开始
-            int maxRow = sheet.getLastRowNum();
-//            从第二行开始获取数据
-            for (int row = 1; row <= maxRow; row++) {
-                //获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
-                int maxRol = sheet.getRow(row).getLastCellNum();
-                System.out.println("--------第" + row + "行的数据如下--------");
-//                for (int rol = 0; rol < maxRol; rol++){
-//                    System.out.print(sheet.getRow(row).getCell(rol) + "  ");
-//                }
-                DataFormatter dataFormatter = new DataFormatter();
-//                获取手机号
-                XSSFCell cell = sheet.getRow(row).getCell(3);
-//                获取的手机号格式有问题需要转换
-                dataFormatter.addFormat("###########",null);
-                String phone = dataFormatter.formatCellValue(cell);
-//                获取名字
-                String name = sheet.getRow(row).getCell(1).toString();
-//                获取备注
-                String remarks = sheet.getRow(row).getCell(4).toString();
-//                获取性别
-                String genderName = sheet.getRow(row).getCell(2).toString();
-                int gender;
-                if ("女".equals(genderName)) {
-                    gender=1;
-                }else {
-                    gender=2;
-                }
-
-                SystemUser systemUser = new SystemUser();
-                systemUser.setRoleId(Long.valueOf(row));
-                systemUser.setAccountName(name);
-                systemUser.setAccountNumber(row+"");
-                systemUser.setAccountPassword("123456");
-                systemUser.setPhoneNumber(phone);
-                systemUser.setEmail("123456@123456");
-                systemUser.setRemarks(remarks);
-                systemUser.setGender(gender);
-                systemUser.setDeleted(0L);
-                systemUser.setWechatId("123456789");
-
-                systemUserService.save(systemUser);
-
-            }
-        }
-    }
-}
+package com.template.controller;
+
+import com.template.annotation.PassToken;
+import com.template.api.ExcelControllerAPI;
+import com.template.model.pojo.SystemUser;
+import com.template.services.SystemUserService;
+import org.apache.poi.ss.usermodel.DataFormatter;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+
+@RestController
+public class ExcelController implements ExcelControllerAPI {
+    @Autowired
+    SystemUserService systemUserService;
+
+    /**
+     * .xlsx格式
+     * @param
+     */
+    @Override
+    @PassToken
+    public void toExcel(String fileUrl) {
+        //创建工作簿对象
+        XSSFWorkbook xssfWorkbook = null;
+        try {
+            xssfWorkbook = new XSSFWorkbook(new FileInputStream(fileUrl));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        //获取工作簿下sheet的个数
+        int sheetNum = xssfWorkbook.getNumberOfSheets();
+        //遍历工作簿中的所有数据
+        for (int i = 0; i < sheetNum; i++) {
+            //读取第i个工作表
+            System.out.println("读取第"+(i+1)+"个sheet");
+            XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
+            //获取最后一行的num,即总行数。此处从0开始
+            int maxRow = sheet.getLastRowNum();
+//            从第二行开始获取数据
+            for (int row = 1; row <= maxRow; row++) {
+                //获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
+                int maxRol = sheet.getRow(row).getLastCellNum();
+                System.out.println("--------第" + row + "行的数据如下--------");
+//                for (int rol = 0; rol < maxRol; rol++){
+//                    System.out.print(sheet.getRow(row).getCell(rol) + "  ");
+//                }
+                DataFormatter dataFormatter = new DataFormatter();
+//                获取手机号
+                XSSFCell cell = sheet.getRow(row).getCell(3);
+//                获取的手机号格式有问题需要转换
+                dataFormatter.addFormat("###########",null);
+                String phone = dataFormatter.formatCellValue(cell);
+//                获取名字
+                String name = sheet.getRow(row).getCell(1).toString();
+//                获取备注
+                String remarks = sheet.getRow(row).getCell(4).toString();
+//                获取性别
+                String genderName = sheet.getRow(row).getCell(2).toString();
+                int gender;
+                if ("女".equals(genderName)) {
+                    gender=1;
+                }else {
+                    gender=2;
+                }
+
+                SystemUser systemUser = new SystemUser();
+                systemUser.setRoleId(Long.valueOf(row));
+                systemUser.setAccountName(name);
+                systemUser.setAccountNumber(row+"");
+                systemUser.setAccountPassword("123456");
+                systemUser.setPhoneNumber(phone);
+                systemUser.setEmail("123456@123456");
+                systemUser.setRemarks(remarks);
+                systemUser.setGender(gender);
+                systemUser.setDeleted(0L);
+                systemUser.setWechatId("123456789");
+
+                systemUserService.save(systemUser);
+
+            }
+        }
+    }
+}

+ 76 - 76
src/main/java/com/template/controller/HotelController.java

@@ -1,76 +1,76 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.HotelControllerAPI;
-import com.template.api.SystemMenuControllerAPI;
-import com.template.mapper.HotelMapper;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import com.template.services.SystemMenuService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class HotelController implements HotelControllerAPI {
-
-    @Autowired
-    private HotelMapper hotelMapper;
-
-
-    @Override
-    @PassToken
-    public CommonResult QueryTownRate() {
-        List<Map<String, String>> townRateList = hotelMapper.getTownRate();
-        if (townRateList.isEmpty()){
-            return CommonResult.ok(townRateList);
-        }
-        return CommonResult.ok(townRateList);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult QueryHotelList(String town, String hName,int pageNum,int pageSize ) {
-        int pageIndex=pageNum==1?0:(pageNum-1)*pageSize;
-        List<Map<String, Object>> hotelList = hotelMapper.getHotelList(town, hName,pageIndex,pageSize);
-        int total=hotelMapper.getTownTotal(town,hName);
-        if (hotelList.isEmpty()){
-            return CommonResult.ok("查询为空",hotelList);
-        }
-        Map<String, Object> resultMap=new HashMap<>();
-        resultMap.put("total",total);
-        resultMap.put("hotelList",hotelList);
-        return CommonResult.ok(resultMap);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult QueryHotelListByName( String hName ) {
-
-        hName=hName!=null?hName:"";
-        List<Map<String, Object>> hotelListByName = hotelMapper.getHotelListByName(hName);
-        if (hotelListByName.isEmpty()){
-            return CommonResult.ok("查询为空",hotelListByName);
-        }
-
-        return CommonResult.ok(hotelListByName);
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.HotelControllerAPI;
+import com.template.api.SystemMenuControllerAPI;
+import com.template.mapper.HotelMapper;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import com.template.services.SystemMenuService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class HotelController implements HotelControllerAPI {
+
+    @Autowired
+    private HotelMapper hotelMapper;
+
+
+    @Override
+    @PassToken
+    public CommonResult QueryTownRate() {
+        List<Map<String, String>> townRateList = hotelMapper.getTownRate();
+        if (townRateList.isEmpty()){
+            return CommonResult.ok(townRateList);
+        }
+        return CommonResult.ok(townRateList);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult QueryHotelList(String town, String hName,int pageNum,int pageSize ) {
+        int pageIndex=pageNum==1?0:(pageNum-1)*pageSize;
+        List<Map<String, Object>> hotelList = hotelMapper.getHotelList(town, hName,pageIndex,pageSize);
+        int total=hotelMapper.getTownTotal(town,hName);
+        if (hotelList.isEmpty()){
+            return CommonResult.ok("查询为空",hotelList);
+        }
+        Map<String, Object> resultMap=new HashMap<>();
+        resultMap.put("total",total);
+        resultMap.put("hotelList",hotelList);
+        return CommonResult.ok(resultMap);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult QueryHotelListByName( String hName ) {
+
+        hName=hName!=null?hName:"";
+        List<Map<String, Object>> hotelListByName = hotelMapper.getHotelListByName(hName);
+        if (hotelListByName.isEmpty()){
+            return CommonResult.ok("查询为空",hotelListByName);
+        }
+
+        return CommonResult.ok(hotelListByName);
+    }
+}
+

+ 32 - 32
src/main/java/com/template/controller/LogInfoController.java

@@ -1,32 +1,32 @@
-package com.template.controller;
-
-import com.template.annotation.PassToken;
-import com.template.api.LogInfoControllerAPI;
-import com.template.model.result.CommonResult;
-import com.template.services.impl.SmsCodeServiceImpl;
-import com.template.services.impl.SystemUserServiceImpl;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-@RestController
-public class LogInfoController implements LogInfoControllerAPI {
-
-
-    @Autowired
-    SystemUserServiceImpl systemUserService;
-
-    @Autowired
-    SmsCodeServiceImpl smsCodeService;
-
-    @Override
-    @PassToken
-    public CommonResult verifyPhone(@RequestParam String phone) {
-        return CommonResult.ok();
-    }
-
-    @Override
-    @PassToken
-    public CommonResult logInfo(String phone, String code) {
-        return smsCodeService.logIn(phone,code);
-    }
-}
+package com.template.controller;
+
+import com.template.annotation.PassToken;
+import com.template.api.LogInfoControllerAPI;
+import com.template.model.result.CommonResult;
+import com.template.services.impl.SmsCodeServiceImpl;
+import com.template.services.impl.SystemUserServiceImpl;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+
+@RestController
+public class LogInfoController implements LogInfoControllerAPI {
+
+
+    @Autowired
+    SystemUserServiceImpl systemUserService;
+
+    @Autowired
+    SmsCodeServiceImpl smsCodeService;
+
+    @Override
+    @PassToken
+    public CommonResult verifyPhone(@RequestParam String phone) {
+        return CommonResult.ok();
+    }
+
+    @Override
+    @PassToken
+    public CommonResult logInfo(String phone, String code) {
+        return smsCodeService.logIn(phone,code);
+    }
+}

+ 161 - 161
src/main/java/com/template/controller/LoginController.java

@@ -1,161 +1,161 @@
-package com.template.controller;
-
-import com.template.annotation.PassToken;
-import com.template.api.LoginControllerAPI;
-import com.template.model.enumModel.eStatu;
-import com.template.model.pojo.RepairAdmin;
-import com.template.model.request.loginRequest;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.LoginVO;
-import com.template.services.RepairAdminService;
-import com.template.common.utils.AesUtils;
-import com.template.common.utils.paramUtils;
-import com.template.common.utils.JWTUtil;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.validation.BindingResult;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestHeader;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * @Author: binguo
- * @Date: 2023/7/5 星期三 9:28
- * @Description: com.template.controller
- * @Version: 1.0
- */
-@RestController
-public class LoginController implements LoginControllerAPI {
-
-    @Autowired
-    private RepairAdminService repairAdminService;
-
-    /**
-     * 查看系统版本号
-     * @return
-     */
-    @Override
-    @PassToken
-    public CommonResult queryReduce() {
-        return CommonResult.ok("当前系统版本为:1V");
-    }
-
-    /**
-     * 注册接口
-     * @param registerdo
-     * account 账号
-     * password 密码
-     * username 昵称
-     * phone 手机号
-     * @return
-     */
-    @Override
-    @PassToken
-    public CommonResult Register(@RequestBody RepairAdmin registerdo, BindingResult bindingResult) {
-        if(registerdo == null){
-            return CommonResult.fail("请传递参数");
-        }
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-        int result = 0;
-        try{
-            result = repairAdminService.insertRepairAdmin(registerdo);
-        }catch (Exception e){
-            if(e.getCause().getMessage().contains("'repair_admin.account_un'")){
-                return CommonResult.fail("该账号已存在!");
-            }
-            return CommonResult.fail("系统异常,注册失败!");
-        }
-        if(result > 0){
-            return CommonResult.ok("注册成功!");
-        }
-        return CommonResult.fail("注册失败!");
-    }
-
-    /**
-     * 登录接口
-     * @param loginRequest
-     * account 账号
-     * password 密码
-     * @return
-     *
-     */
-    @Override
-    @PassToken
-    public CommonResult Login(@RequestBody loginRequest loginRequest, BindingResult bindingResult) {
-        if(loginRequest == null){
-            return CommonResult.fail("请传递参数");
-        }
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-
-        RepairAdmin result = repairAdminService.getRepairByAccount(loginRequest.getAccount());
-        if(result == null){
-            return CommonResult.fail("账号或密码错误");
-        }
-
-        if(result.getStatu() == eStatu.Freeze.getValue()){
-            return CommonResult.fail("该账号已被冻结");
-        }
-
-        String encPassword = AesUtils.encrypt(loginRequest.getPassword());
-        if(!encPassword.equals(result.getPassword())){
-            return CommonResult.fail("密码错误");
-        }
-
-        String token = JWTUtil.getToken(result);
-        LoginVO login = new LoginVO();
-        login.setToken(token);
-        login.setTokenTtl(JWTUtil.getExpired());
-        login.setUserName(result.getUsername());
-        login.setUserhead(AesUtils.encrypt(result.getId()));
-
-        return CommonResult.ok("登录成功",login);
-    }
-
-    /**
-     * 修改密码
-     * @param cpr
-     * oldPassword 旧密码
-     * newPassword 新密码
-     * confirmPassword 确认密码
-     * @param userhead
-     * @param bindingResult
-     * @return
-     */
-    @Override
-    public CommonResult ChangePassword(com.repair.model.request.changePasswordRequest cpr, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-
-        if(!cpr.getNewPassword().equals(cpr.getConfirmPassword())){
-            return CommonResult.fail("确认密码和新密码不一致!");
-        }
-
-        String userID = AesUtils.decrypt(userhead);
-        RepairAdmin operateData = repairAdminService.getRepairById(userID);
-        if(operateData == null){
-            return CommonResult.fail("当前账号不合法!");
-        }
-
-        if(operateData.getStatu() == eStatu.Freeze.getValue()){
-            return CommonResult.fail("该账号已被冻结");
-        }
-
-        if(!AesUtils.encrypt(cpr.getOldPassword()).equals(operateData.getPassword())){
-            return CommonResult.fail("原密码错误!");
-        }
-
-        RepairAdmin ra = new RepairAdmin();
-        ra.setId(userID);
-        ra.setPassword(AesUtils.encrypt(cpr.getNewPassword()));
-        int result = repairAdminService.updateRepairAdmin(ra);
-
-        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
-    }
-}
+package com.template.controller;
+
+import com.template.annotation.PassToken;
+import com.template.api.LoginControllerAPI;
+import com.template.model.enumModel.eStatu;
+import com.template.model.pojo.RepairAdmin;
+import com.template.model.request.loginRequest;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.LoginVO;
+import com.template.services.RepairAdminService;
+import com.template.common.utils.AesUtils;
+import com.template.common.utils.paramUtils;
+import com.template.common.utils.JWTUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/7/5 星期三 9:28
+ * @Description: com.template.controller
+ * @Version: 1.0
+ */
+@RestController
+public class LoginController implements LoginControllerAPI {
+
+    @Autowired
+    private RepairAdminService repairAdminService;
+
+    /**
+     * 查看系统版本号
+     * @return
+     */
+    @Override
+    @PassToken
+    public CommonResult queryReduce() {
+        return CommonResult.ok("当前系统版本为:1V");
+    }
+
+    /**
+     * 注册接口
+     * @param registerdo
+     * account 账号
+     * password 密码
+     * username 昵称
+     * phone 手机号
+     * @return
+     */
+    @Override
+    @PassToken
+    public CommonResult Register(@RequestBody RepairAdmin registerdo, BindingResult bindingResult) {
+        if(registerdo == null){
+            return CommonResult.fail("请传递参数");
+        }
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+        int result = 0;
+        try{
+            result = repairAdminService.insertRepairAdmin(registerdo);
+        }catch (Exception e){
+            if(e.getCause().getMessage().contains("'repair_admin.account_un'")){
+                return CommonResult.fail("该账号已存在!");
+            }
+            return CommonResult.fail("系统异常,注册失败!");
+        }
+        if(result > 0){
+            return CommonResult.ok("注册成功!");
+        }
+        return CommonResult.fail("注册失败!");
+    }
+
+    /**
+     * 登录接口
+     * @param loginRequest
+     * account 账号
+     * password 密码
+     * @return
+     *
+     */
+    @Override
+    @PassToken
+    public CommonResult Login(@RequestBody loginRequest loginRequest, BindingResult bindingResult) {
+        if(loginRequest == null){
+            return CommonResult.fail("请传递参数");
+        }
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+
+        RepairAdmin result = repairAdminService.getRepairByAccount(loginRequest.getAccount());
+        if(result == null){
+            return CommonResult.fail("账号或密码错误");
+        }
+
+        if(result.getStatu() == eStatu.Freeze.getValue()){
+            return CommonResult.fail("该账号已被冻结");
+        }
+
+        String encPassword = AesUtils.encrypt(loginRequest.getPassword());
+        if(!encPassword.equals(result.getPassword())){
+            return CommonResult.fail("密码错误");
+        }
+
+        String token = JWTUtil.getToken(result);
+        LoginVO login = new LoginVO();
+        login.setToken(token);
+        login.setTokenTtl(JWTUtil.getExpired());
+        login.setUserName(result.getUsername());
+        login.setUserhead(AesUtils.encrypt(result.getId()));
+
+        return CommonResult.ok("登录成功",login);
+    }
+
+    /**
+     * 修改密码
+     * @param cpr
+     * oldPassword 旧密码
+     * newPassword 新密码
+     * confirmPassword 确认密码
+     * @param userhead
+     * @param bindingResult
+     * @return
+     */
+    @Override
+    public CommonResult ChangePassword(com.repair.model.request.changePasswordRequest cpr, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+
+        if(!cpr.getNewPassword().equals(cpr.getConfirmPassword())){
+            return CommonResult.fail("确认密码和新密码不一致!");
+        }
+
+        String userID = AesUtils.decrypt(userhead);
+        RepairAdmin operateData = repairAdminService.getRepairById(userID);
+        if(operateData == null){
+            return CommonResult.fail("当前账号不合法!");
+        }
+
+        if(operateData.getStatu() == eStatu.Freeze.getValue()){
+            return CommonResult.fail("该账号已被冻结");
+        }
+
+        if(!AesUtils.encrypt(cpr.getOldPassword()).equals(operateData.getPassword())){
+            return CommonResult.fail("原密码错误!");
+        }
+
+        RepairAdmin ra = new RepairAdmin();
+        ra.setId(userID);
+        ra.setPassword(AesUtils.encrypt(cpr.getNewPassword()));
+        int result = repairAdminService.updateRepairAdmin(ra);
+
+        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
+    }
+}

+ 120 - 120
src/main/java/com/template/controller/ParkingController.java

@@ -1,120 +1,120 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.HotelControllerAPI;
-import com.template.api.ParkingControllerAPI;
-import com.template.common.utils.TimeExchange;
-import com.template.mapper.HotelMapper;
-import com.template.mapper.ParkingMapper;
-import com.template.model.result.CommonResult;
-import com.template.scheduled.ScheduledService;
-import org.apache.commons.lang3.time.DateUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class ParkingController implements ParkingControllerAPI {
-
-    @Autowired
-    private ParkingMapper parkingMapper;
-
-
-
-
-    @Override
-    @PassToken
-    public CommonResult getParkingCount() {
-        List<Map<String, String>> parkingCount = parkingMapper.getParkingCount();
-        if(parkingCount.isEmpty()){
-            return CommonResult.fail("数据为空");
-        }
-        return CommonResult.ok(parkingCount);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getParkingSpace() {
-        List<Map<String, String>> parkingSpace= parkingMapper.getParkingSpace();
-        if(parkingSpace.isEmpty()){
-            return CommonResult.fail("数据为空");
-        }
-        return CommonResult.ok(parkingSpace);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getParkingByTown() {
-        List<Map<String, String>> parkingByTown= parkingMapper.getParkingByTown();
-        if(parkingByTown.isEmpty()){
-            return CommonResult.fail("数据为空");
-        }
-        return CommonResult.ok(parkingByTown);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getAllParkingInfo() {
-        List<Map<String, String>> allParkingInfo= parkingMapper.getAllParkingInfo();
-        if(allParkingInfo.isEmpty()){
-            return CommonResult.fail("数据为空");
-        }
-        return CommonResult.ok(allParkingInfo);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getParkingInfoById(String id) {
-        List<Map<String, String>> parkingInfoById= parkingMapper.getParkingInfoById(id);
-        if(parkingInfoById.isEmpty()){
-            return CommonResult.fail("实时数据为空");
-        }
-        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH");
-        String endTime=sp.format(new Date());
-        String startTime= sp.format(DateUtils.addHours(new Date(), -24));
-        List<Map<String, String>> parkingInfoHis = parkingMapper.getParkingInfoHis(id, startTime, endTime);
-        Map<String, Object> resultMap=new HashMap<>();
-        resultMap.put("parkingInfo",parkingInfoById);
-        resultMap.put("parkingHistory",parkingInfoHis);
-        return CommonResult.ok(resultMap);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getParkingInfoByTime(String dayId) {
-
-        try {
-            TimeExchange.StringToDate(dayId,"yyyy-MM-dd HH");
-        } catch (Exception e) {
-            e.printStackTrace();
-            return CommonResult.fail(dayId+"日期格式不符yyyy-MM-dd HH");
-        }
-        String result=this.getParkingInfo(dayId);
-        return CommonResult.ok(result);
-    }
-
-    public String getParkingInfo(String dayId) {
-
-        if(dayId!=null&&dayId!=""){
-            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH");
-            dayId=sp.format(new Date());
-        }
-        int a= parkingMapper.getTrendByTime(dayId);
-        return "停车场实时数据同步结束,当前账期"+dayId+" 更新了"+a+"条数据";
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.HotelControllerAPI;
+import com.template.api.ParkingControllerAPI;
+import com.template.common.utils.TimeExchange;
+import com.template.mapper.HotelMapper;
+import com.template.mapper.ParkingMapper;
+import com.template.model.result.CommonResult;
+import com.template.scheduled.ScheduledService;
+import org.apache.commons.lang3.time.DateUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class ParkingController implements ParkingControllerAPI {
+
+    @Autowired
+    private ParkingMapper parkingMapper;
+
+
+
+
+    @Override
+    @PassToken
+    public CommonResult getParkingCount() {
+        List<Map<String, String>> parkingCount = parkingMapper.getParkingCount();
+        if(parkingCount.isEmpty()){
+            return CommonResult.fail("数据为空");
+        }
+        return CommonResult.ok(parkingCount);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getParkingSpace() {
+        List<Map<String, String>> parkingSpace= parkingMapper.getParkingSpace();
+        if(parkingSpace.isEmpty()){
+            return CommonResult.fail("数据为空");
+        }
+        return CommonResult.ok(parkingSpace);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getParkingByTown() {
+        List<Map<String, String>> parkingByTown= parkingMapper.getParkingByTown();
+        if(parkingByTown.isEmpty()){
+            return CommonResult.fail("数据为空");
+        }
+        return CommonResult.ok(parkingByTown);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getAllParkingInfo() {
+        List<Map<String, String>> allParkingInfo= parkingMapper.getAllParkingInfo();
+        if(allParkingInfo.isEmpty()){
+            return CommonResult.fail("数据为空");
+        }
+        return CommonResult.ok(allParkingInfo);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getParkingInfoById(String id) {
+        List<Map<String, String>> parkingInfoById= parkingMapper.getParkingInfoById(id);
+        if(parkingInfoById.isEmpty()){
+            return CommonResult.fail("实时数据为空");
+        }
+        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH");
+        String endTime=sp.format(new Date());
+        String startTime= sp.format(DateUtils.addHours(new Date(), -24));
+        List<Map<String, String>> parkingInfoHis = parkingMapper.getParkingInfoHis(id, startTime, endTime);
+        Map<String, Object> resultMap=new HashMap<>();
+        resultMap.put("parkingInfo",parkingInfoById);
+        resultMap.put("parkingHistory",parkingInfoHis);
+        return CommonResult.ok(resultMap);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getParkingInfoByTime(String dayId) {
+
+        try {
+            TimeExchange.StringToDate(dayId,"yyyy-MM-dd HH");
+        } catch (Exception e) {
+            e.printStackTrace();
+            return CommonResult.fail(dayId+"日期格式不符yyyy-MM-dd HH");
+        }
+        String result=this.getParkingInfo(dayId);
+        return CommonResult.ok(result);
+    }
+
+    public String getParkingInfo(String dayId) {
+
+        if(dayId!=null&&dayId!=""){
+            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH");
+            dayId=sp.format(new Date());
+        }
+        int a= parkingMapper.getTrendByTime(dayId);
+        return "停车场实时数据同步结束,当前账期"+dayId+" 更新了"+a+"条数据";
+    }
+}
+

+ 163 - 163
src/main/java/com/template/controller/RepairAdminController.java

@@ -1,163 +1,163 @@
-package com.template.controller;
-
-
-import com.template.api.RepairAdminControllerAPI;
-import com.template.common.utils.AesUtils;
-import com.template.common.utils.paramUtils;
-import com.template.model.enumModel.eIsSuper;
-import com.template.model.enumModel.eStatu;
-import com.template.model.pojo.RepairAdmin;
-import com.template.model.result.CommonResult;
-import com.template.model.result.PageUtils;
-import com.template.services.RepairAdminService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.validation.BindingResult;
-import org.springframework.web.bind.annotation.*;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-07-05
- */
-@RestController
-public class RepairAdminController implements RepairAdminControllerAPI {
-
-    @Autowired
-    private RepairAdminService repairAdminService;
-
-    /**
-     * 添加账号数据
-     *
-     * @param ra account 账号
-     *           password 密码
-     *           username 用户名称
-     *           phone 手机号
-     * @return
-     */
-    @Override
-    public CommonResult InsertRepairAdmin(@RequestBody RepairAdmin ra, BindingResult bindingResult) {
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-        int result = 0; // 帮我们自动生成id
-        try {
-            result = repairAdminService.insertRepairAdmin(ra);
-        } catch (Exception e) {
-            if (e.getCause().getMessage().contains("'repair_admin.account_un'")) {
-                return CommonResult.fail("该账号已存在!");
-            }
-            return CommonResult.fail("系统异常,添加失败!");
-        }
-        return result > 0 ? CommonResult.ok() : CommonResult.fail();
-    }
-
-    /**
-     * 查询账户列表数据
-     *
-     * @param currentPage 当前页
-     * @param pageCount   一页数据条数
-     * @param account     账号
-     * @param phone       手机号
-     * @param userName    账号名称
-     * @return
-     */
-    @Override
-    public CommonResult queryPageRepairAdmins(@RequestParam int currentPage, @RequestParam int pageCount, String account, String phone, String userName) {
-        PageUtils<RepairAdmin> result = repairAdminService.queryPageList(currentPage, pageCount, account, phone, userName);
-
-        return CommonResult.ok(result);
-    }
-
-    /**
-     * 根据ID冻结账号账号数据
-     *
-     * @param frar id 数据ID
-     *             statu 状态
-     *             正常:0;冻结:1
-     * @return
-     */
-    @Override
-    public CommonResult freezeRepairAdminById(@RequestBody com.repair.model.request.freezeRepairAdminRequest frar, BindingResult bindingResult) {
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-        RepairAdmin data = repairAdminService.getRepairById(frar.getId());
-        if (data == null) {
-            return CommonResult.fail("当前数据不存在,解冻失败!");
-        }
-        if (data.getStatu() == frar.getStatu()) {
-            String Message = frar.getStatu() == eStatu.Freeze.getValue() ? "当前处于冻结状态,请勿重复操作!" : "当前处于未冻结状态,请勿重复操作!";
-            return CommonResult.fail(Message);
-        }
-
-        String success = frar.getStatu() == eStatu.Freeze.getValue() ? "冻结成功!" : "解冻成功";
-        String fail = frar.getStatu() == eStatu.Freeze.getValue() ? "冻结失败!" : "解冻失败";
-        RepairAdmin ra = new RepairAdmin();
-        ra.setId(frar.getId());
-        ra.setStatu(frar.getStatu());
-        int result = repairAdminService.updateRepairAdmin(ra);
-        System.out.println(result);
-        return result > 0 ? CommonResult.ok(success) : CommonResult.fail(fail);
-    }
-
-    /**
-     * 根据ID删除账号数据
-     *
-     * @param id id 数据ID
-     * @return
-     */
-    @Override
-    public CommonResult deleteRepairAdminById(@RequestParam String id) {
-        RepairAdmin data = repairAdminService.getRepairById(id);
-        if (data == null) {
-            return CommonResult.fail("当前数据不存在,删除失败!");
-        }
-
-        int result = repairAdminService.deleteRepairAdminById(id);
-
-        return result > 0 ? CommonResult.ok() : CommonResult.fail();
-    }
-
-    /**
-     * 编辑账号
-     *
-     * @param ra id 数据ID
-     *           username 账号名称
-     *           phone 手机号
-     *           password 密码
-     * @return
-     */
-    @Override
-    public CommonResult updateRepairAdminById(com.repair.model.request.updateRepairAdminRequest ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
-        if (bindingResult.hasErrors()) {
-            String st = paramUtils.getParamError(bindingResult);
-            return CommonResult.fail(st);
-        }
-
-        RepairAdmin data = repairAdminService.getRepairById(ra.getId());
-        if (data == null) {
-            return CommonResult.fail("当前数据不存在,编辑失败!");
-        }
-
-        //只有操作管理员才能编辑他人的密码
-        String userID = AesUtils.decrypt(userhead);
-        if (ra.getPassword() != null && !userID.equals(ra.getId())) {
-            RepairAdmin operateData = repairAdminService.getRepairById(userID);
-            if(operateData == null){
-                return CommonResult.fail("操作身份不合法,编辑失败!");
-            }
-            if(!data.getPassword().equals(AesUtils.encrypt(ra.getPassword())) && operateData.getIsSuper() != eIsSuper.Super.getValue()){
-                return CommonResult.fail("只有超级管理员才能更改密码!");
-            }
-        }
-
-        int result = repairAdminService.updateRepaiRadmin(ra);
-        return result > 0 ? CommonResult.ok("编辑成功") : CommonResult.fail("编辑失败");
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.api.RepairAdminControllerAPI;
+import com.template.common.utils.AesUtils;
+import com.template.common.utils.paramUtils;
+import com.template.model.enumModel.eIsSuper;
+import com.template.model.enumModel.eStatu;
+import com.template.model.pojo.RepairAdmin;
+import com.template.model.result.CommonResult;
+import com.template.model.result.PageUtils;
+import com.template.services.RepairAdminService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.annotation.*;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-07-05
+ */
+@RestController
+public class RepairAdminController implements RepairAdminControllerAPI {
+
+    @Autowired
+    private RepairAdminService repairAdminService;
+
+    /**
+     * 添加账号数据
+     *
+     * @param ra account 账号
+     *           password 密码
+     *           username 用户名称
+     *           phone 手机号
+     * @return
+     */
+    @Override
+    public CommonResult InsertRepairAdmin(@RequestBody RepairAdmin ra, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+        int result = 0; // 帮我们自动生成id
+        try {
+            result = repairAdminService.insertRepairAdmin(ra);
+        } catch (Exception e) {
+            if (e.getCause().getMessage().contains("'repair_admin.account_un'")) {
+                return CommonResult.fail("该账号已存在!");
+            }
+            return CommonResult.fail("系统异常,添加失败!");
+        }
+        return result > 0 ? CommonResult.ok() : CommonResult.fail();
+    }
+
+    /**
+     * 查询账户列表数据
+     *
+     * @param currentPage 当前页
+     * @param pageCount   一页数据条数
+     * @param account     账号
+     * @param phone       手机号
+     * @param userName    账号名称
+     * @return
+     */
+    @Override
+    public CommonResult queryPageRepairAdmins(@RequestParam int currentPage, @RequestParam int pageCount, String account, String phone, String userName) {
+        PageUtils<RepairAdmin> result = repairAdminService.queryPageList(currentPage, pageCount, account, phone, userName);
+
+        return CommonResult.ok(result);
+    }
+
+    /**
+     * 根据ID冻结账号账号数据
+     *
+     * @param frar id 数据ID
+     *             statu 状态
+     *             正常:0;冻结:1
+     * @return
+     */
+    @Override
+    public CommonResult freezeRepairAdminById(@RequestBody com.repair.model.request.freezeRepairAdminRequest frar, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+        RepairAdmin data = repairAdminService.getRepairById(frar.getId());
+        if (data == null) {
+            return CommonResult.fail("当前数据不存在,解冻失败!");
+        }
+        if (data.getStatu() == frar.getStatu()) {
+            String Message = frar.getStatu() == eStatu.Freeze.getValue() ? "当前处于冻结状态,请勿重复操作!" : "当前处于未冻结状态,请勿重复操作!";
+            return CommonResult.fail(Message);
+        }
+
+        String success = frar.getStatu() == eStatu.Freeze.getValue() ? "冻结成功!" : "解冻成功";
+        String fail = frar.getStatu() == eStatu.Freeze.getValue() ? "冻结失败!" : "解冻失败";
+        RepairAdmin ra = new RepairAdmin();
+        ra.setId(frar.getId());
+        ra.setStatu(frar.getStatu());
+        int result = repairAdminService.updateRepairAdmin(ra);
+        System.out.println(result);
+        return result > 0 ? CommonResult.ok(success) : CommonResult.fail(fail);
+    }
+
+    /**
+     * 根据ID删除账号数据
+     *
+     * @param id id 数据ID
+     * @return
+     */
+    @Override
+    public CommonResult deleteRepairAdminById(@RequestParam String id) {
+        RepairAdmin data = repairAdminService.getRepairById(id);
+        if (data == null) {
+            return CommonResult.fail("当前数据不存在,删除失败!");
+        }
+
+        int result = repairAdminService.deleteRepairAdminById(id);
+
+        return result > 0 ? CommonResult.ok() : CommonResult.fail();
+    }
+
+    /**
+     * 编辑账号
+     *
+     * @param ra id 数据ID
+     *           username 账号名称
+     *           phone 手机号
+     *           password 密码
+     * @return
+     */
+    @Override
+    public CommonResult updateRepairAdminById(com.repair.model.request.updateRepairAdminRequest ra, @RequestHeader("user_head") String userhead, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            String st = paramUtils.getParamError(bindingResult);
+            return CommonResult.fail(st);
+        }
+
+        RepairAdmin data = repairAdminService.getRepairById(ra.getId());
+        if (data == null) {
+            return CommonResult.fail("当前数据不存在,编辑失败!");
+        }
+
+        //只有操作管理员才能编辑他人的密码
+        String userID = AesUtils.decrypt(userhead);
+        if (ra.getPassword() != null && !userID.equals(ra.getId())) {
+            RepairAdmin operateData = repairAdminService.getRepairById(userID);
+            if(operateData == null){
+                return CommonResult.fail("操作身份不合法,编辑失败!");
+            }
+            if(!data.getPassword().equals(AesUtils.encrypt(ra.getPassword())) && operateData.getIsSuper() != eIsSuper.Super.getValue()){
+                return CommonResult.fail("只有超级管理员才能更改密码!");
+            }
+        }
+
+        int result = repairAdminService.updateRepaiRadmin(ra);
+        return result > 0 ? CommonResult.ok("编辑成功") : CommonResult.fail("编辑失败");
+    }
+}
+

+ 42 - 42
src/main/java/com/template/controller/SmsCodeController.java

@@ -1,42 +1,42 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.SmsCodeControllerAPI;
-import com.template.model.pojo.SmsCode;
-import com.template.model.result.CommonResult;
-import com.template.services.SmsCodeService;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import org.springframework.web.bind.annotation.RestController;
-
-import java.util.Date;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-04-20
- */
-@RestController
-public class SmsCodeController implements SmsCodeControllerAPI {
-
-    @Autowired
-    private SmsCodeService smsCodeService;
-
-    @Override
-    @PassToken
-    public CommonResult InsertSmsCode() {
-        SmsCode smsCode = new SmsCode();
-        smsCode.setPhoneNumber("123456789");
-        smsCode.setCode("123456");
-        long time = new Date().getTime() + 60000L;
-        smsCode.setExpirationTime(new Date(time));
-        smsCode.setIsVerify("0");
-        smsCodeService.save(smsCode);
-        return null;
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.SmsCodeControllerAPI;
+import com.template.model.pojo.SmsCode;
+import com.template.model.result.CommonResult;
+import com.template.services.SmsCodeService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.Date;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-04-20
+ */
+@RestController
+public class SmsCodeController implements SmsCodeControllerAPI {
+
+    @Autowired
+    private SmsCodeService smsCodeService;
+
+    @Override
+    @PassToken
+    public CommonResult InsertSmsCode() {
+        SmsCode smsCode = new SmsCode();
+        smsCode.setPhoneNumber("123456789");
+        smsCode.setCode("123456");
+        long time = new Date().getTime() + 60000L;
+        smsCode.setExpirationTime(new Date(time));
+        smsCode.setIsVerify("0");
+        smsCodeService.save(smsCode);
+        return null;
+    }
+}
+

+ 57 - 57
src/main/java/com/template/controller/SpecialityController.java

@@ -1,57 +1,57 @@
-package com.template.controller;
-
-
-import com.template.annotation.PassToken;
-import com.template.api.SpecialityControllerAPI;
-import com.template.api.SystemMenuControllerAPI;
-import com.template.mapper.SpecialityMapper;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import com.template.services.SystemMenuService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class SpecialityController implements SpecialityControllerAPI {
-
-    @Autowired
-    private SpecialityMapper specialityMapper;
-
-
-    @Override
-    @PassToken
-    public CommonResult getTopByAmount() {
-        List<Map<String, String>> topByAmount = specialityMapper.getTopByAmount();
-        if (topByAmount.isEmpty()){
-            return CommonResult.ok("查询为空");
-        }
-        return CommonResult.ok(topByAmount);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getMonthTrend() {
-        List<Map<String, String>> monthTrend = specialityMapper.getMonthTrend();
-        if (monthTrend.isEmpty()){
-            return CommonResult.ok("查询为空");
-        }
-        return CommonResult.ok(monthTrend);
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.annotation.PassToken;
+import com.template.api.SpecialityControllerAPI;
+import com.template.api.SystemMenuControllerAPI;
+import com.template.mapper.SpecialityMapper;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import com.template.services.SystemMenuService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class SpecialityController implements SpecialityControllerAPI {
+
+    @Autowired
+    private SpecialityMapper specialityMapper;
+
+
+    @Override
+    @PassToken
+    public CommonResult getTopByAmount() {
+        List<Map<String, String>> topByAmount = specialityMapper.getTopByAmount();
+        if (topByAmount.isEmpty()){
+            return CommonResult.ok("查询为空");
+        }
+        return CommonResult.ok(topByAmount);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getMonthTrend() {
+        List<Map<String, String>> monthTrend = specialityMapper.getMonthTrend();
+        if (monthTrend.isEmpty()){
+            return CommonResult.ok("查询为空");
+        }
+        return CommonResult.ok(monthTrend);
+    }
+}
+

+ 110 - 110
src/main/java/com/template/controller/SystemMenuController.java

@@ -1,110 +1,110 @@
-package com.template.controller;
-
-
-import com.template.api.SystemMenuControllerAPI;
-import com.template.model.pojo.SystemMenu;
-import com.template.model.result.CommonResult;
-import com.template.model.vo.SystemMenuTreeVo;
-import com.template.model.vo.SystemMenuVo;
-import com.template.services.SystemMenuService;
-import com.template.annotation.PassToken;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class SystemMenuController implements SystemMenuControllerAPI {
-
-    @Autowired
-    private SystemMenuService systemMenuService;
-
-    @Override
-    @PassToken
-    public CommonResult<Integer> InsertPlaybackRecord(@RequestBody SystemMenu pb){
-        CommonResult<Integer> result = systemMenuService.insertPlaybackRecord(pb); // 帮我们自动生成id
-        return result;
-    }
-
-    @Override
-    @PassToken
-    public CommonResult<List<SystemMenu>> QueryPlaybackRecords(HttpServletRequest request) {
-        CommonResult<List<SystemMenu>> result = systemMenuService.getPlaybackRecords();
-        return result;
-    }
-
-    @Override
-    @PassToken
-    public CommonResult<List<SystemMenuVo>> QueryPlaybackRecordBySql() {
-        CommonResult<List<SystemMenuVo>> result = systemMenuService.getPlaybackRecordBySql();
-        return result;
-    }
-
-    @Override
-    @PassToken
-    public CommonResult<List<SystemMenu>> QueryPlaybackRecords() {
-        return systemMenuService.getSystemMenus();
-    }
-
-    @Override
-    @PassToken
-    public CommonResult InsertSystemMenu(SystemMenu systemMenu) {
-        return systemMenuService.insertSystemMenus(systemMenu);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult DeleteSystemMenu(Integer userID) {
-        return systemMenuService.deleteSystemMenu(userID);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult<List<SystemMenuTreeVo>> QueryMenuTreeRecords() {
-        List<SystemMenuTreeVo> newTrees = new ArrayList<>();
-
-        newTrees = QueryMenuTreeRecords(0L);
-
-        return CommonResult.ok().setResult(newTrees);
-    }
-
-    /*
-    根据父类ID获取树形菜单数据
-     */
-    private List<SystemMenuTreeVo> QueryMenuTreeRecords(Long parentID){
-        List<SystemMenuTreeVo> newTrees = new ArrayList<>();
-
-        List<SystemMenu> datas = systemMenuService.getSystemMenusByParentId(parentID).getData();
-
-        for (SystemMenu data : datas) {
-            SystemMenuTreeVo item = SystemMenuTreeVo.builder()
-                    .id(data.getId())
-                    .parentId(data.getMenuParentId())
-                    .menuName(data.getMenuName())
-                    .build();
-            List<SystemMenuTreeVo> news = QueryMenuTreeRecords(item.getId());
-            if (news == null || news.size() == 0) {
-                newTrees.add(item);
-                continue;
-            }else {
-                item.setChildren(news);
-                newTrees.add(item);
-            }
-        }
-
-        return  newTrees;
-    }
-}
-
+package com.template.controller;
+
+
+import com.template.api.SystemMenuControllerAPI;
+import com.template.model.pojo.SystemMenu;
+import com.template.model.result.CommonResult;
+import com.template.model.vo.SystemMenuTreeVo;
+import com.template.model.vo.SystemMenuVo;
+import com.template.services.SystemMenuService;
+import com.template.annotation.PassToken;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class SystemMenuController implements SystemMenuControllerAPI {
+
+    @Autowired
+    private SystemMenuService systemMenuService;
+
+    @Override
+    @PassToken
+    public CommonResult<Integer> InsertPlaybackRecord(@RequestBody SystemMenu pb){
+        CommonResult<Integer> result = systemMenuService.insertPlaybackRecord(pb); // 帮我们自动生成id
+        return result;
+    }
+
+    @Override
+    @PassToken
+    public CommonResult<List<SystemMenu>> QueryPlaybackRecords(HttpServletRequest request) {
+        CommonResult<List<SystemMenu>> result = systemMenuService.getPlaybackRecords();
+        return result;
+    }
+
+    @Override
+    @PassToken
+    public CommonResult<List<SystemMenuVo>> QueryPlaybackRecordBySql() {
+        CommonResult<List<SystemMenuVo>> result = systemMenuService.getPlaybackRecordBySql();
+        return result;
+    }
+
+    @Override
+    @PassToken
+    public CommonResult<List<SystemMenu>> QueryPlaybackRecords() {
+        return systemMenuService.getSystemMenus();
+    }
+
+    @Override
+    @PassToken
+    public CommonResult InsertSystemMenu(SystemMenu systemMenu) {
+        return systemMenuService.insertSystemMenus(systemMenu);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult DeleteSystemMenu(Integer userID) {
+        return systemMenuService.deleteSystemMenu(userID);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult<List<SystemMenuTreeVo>> QueryMenuTreeRecords() {
+        List<SystemMenuTreeVo> newTrees = new ArrayList<>();
+
+        newTrees = QueryMenuTreeRecords(0L);
+
+        return CommonResult.ok().setResult(newTrees);
+    }
+
+    /*
+    根据父类ID获取树形菜单数据
+     */
+    private List<SystemMenuTreeVo> QueryMenuTreeRecords(Long parentID){
+        List<SystemMenuTreeVo> newTrees = new ArrayList<>();
+
+        List<SystemMenu> datas = systemMenuService.getSystemMenusByParentId(parentID).getData();
+
+        for (SystemMenu data : datas) {
+            SystemMenuTreeVo item = SystemMenuTreeVo.builder()
+                    .id(data.getId())
+                    .parentId(data.getMenuParentId())
+                    .menuName(data.getMenuName())
+                    .build();
+            List<SystemMenuTreeVo> news = QueryMenuTreeRecords(item.getId());
+            if (news == null || news.size() == 0) {
+                newTrees.add(item);
+                continue;
+            }else {
+                item.setChildren(news);
+                newTrees.add(item);
+            }
+        }
+
+        return  newTrees;
+    }
+}
+

+ 122 - 122
src/main/java/com/template/controller/ToiletBaseController.java

@@ -1,122 +1,122 @@
-package com.template.controller;
-
-
-import com.alibaba.fastjson.JSONObject;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.template.annotation.PassToken;
-import com.template.api.BookingControllerAPI;
-import com.template.api.ToiletBaseControllerAPI;
-import com.template.mapper.BookingMapper;
-import com.template.mapper.ToiletBaseMapper;
-import com.template.model.result.CommonResult;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestTemplate;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class ToiletBaseController implements ToiletBaseControllerAPI {
-
-
-    @Value("${diseaseRightUrl}")
-    String url;
-
-    @Autowired
-    private ToiletBaseMapper toiletBaseMapper;
-
-
-    @Override
-    @PassToken
-    public CommonResult getToiletBaseCount() {
-        List<Map<String, String>> toiletBaseCount = toiletBaseMapper.getToiletBaseCount();
-        if (toiletBaseCount.isEmpty()){
-            return CommonResult.ok(toiletBaseCount);
-        }
-        return CommonResult.ok(toiletBaseCount);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getToiletBaseInfo() {
-        List<Map<String, String>> toiletBaseInfo = toiletBaseMapper.getToiletBaseInfo();
-        if (toiletBaseInfo.isEmpty()){
-            return CommonResult.ok(toiletBaseInfo);
-        }
-        return CommonResult.ok(toiletBaseInfo);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getToiletRealTime() {
-        RestTemplate client = new RestTemplate();
-        List<Map<String, String>> toiletBaseInfo = toiletBaseMapper.getToiletBaseInfo();
-        int ToiletCount=toiletBaseInfo.size();
-        int intoNum=0;
-        if(!toiletBaseInfo.isEmpty()){
-            for (Map<String, String> infoMap:toiletBaseInfo) {
-                String id=String.valueOf(infoMap.get("id"));
-                ResponseEntity<String> responseEntity = client.getForEntity(url+id, String.class);
-                String body = responseEntity.getBody();
-                if (!responseEntity.getStatusCode().is2xxSuccessful()) {
-                    continue;
-                }
-                if ("false".equals(JSONObject.parseObject(body).getString("success"))) {
-                    return CommonResult.fail("请求实时数据异常:"+JSONObject.parseObject(body).getString("message"));
-                }
-                JSONObject jsonObject=JSONObject.parseObject(body).getJSONObject("data");
-                //入流量
-                int dataOfMan=jsonObject.getJSONObject("dataOfMan").getInteger("intoNum");
-                int dataOfWoman=jsonObject.getJSONObject("dataOfWoman").getInteger("intoNum");
-                int dataOfThird=jsonObject.getJSONObject("dataOfThird").getInteger("intoNum");
-                intoNum=intoNum+dataOfMan+dataOfWoman+dataOfThird;
-            }
-        }
-        Map<String, Object> resultMap=new HashMap<>();
-        resultMap.put("ToiletCount",ToiletCount);
-       Long intoNumTotal= toiletBaseMapper.getToiletBaseInfoHis();
-        resultMap.put("intoNumTotal",intoNumTotal);
-        resultMap.put("intoNum",intoNum);
-        return CommonResult.ok(resultMap);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getToiletRealTimeById(String toiletId) {
-        if("".equals(toiletId)){
-            return CommonResult.fail("请求厕所实时数据toiletId不能为空");
-        }
-        RestTemplate client = new RestTemplate();
-        ResponseEntity<String> responseEntity = client.getForEntity(url+toiletId, String.class);
-        String body = responseEntity.getBody();
-        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
-            return CommonResult.fail("请求厕所实时数据异常");
-        }
-        if ("false".equals(JSONObject.parseObject(body).getString("success"))) {
-            return CommonResult.fail("请求实时数据异常:"+JSONObject.parseObject(body).getString("message"));
-        }
-        JSONObject jsonObject=JSONObject.parseObject(body).getJSONObject("data");
-        return CommonResult.ok(jsonObject);
-    }
-}
-
+package com.template.controller;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.template.annotation.PassToken;
+import com.template.api.BookingControllerAPI;
+import com.template.api.ToiletBaseControllerAPI;
+import com.template.mapper.BookingMapper;
+import com.template.mapper.ToiletBaseMapper;
+import com.template.model.result.CommonResult;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class ToiletBaseController implements ToiletBaseControllerAPI {
+
+
+    @Value("${diseaseRightUrl}")
+    String url;
+
+    @Autowired
+    private ToiletBaseMapper toiletBaseMapper;
+
+
+    @Override
+    @PassToken
+    public CommonResult getToiletBaseCount() {
+        List<Map<String, String>> toiletBaseCount = toiletBaseMapper.getToiletBaseCount();
+        if (toiletBaseCount.isEmpty()){
+            return CommonResult.ok(toiletBaseCount);
+        }
+        return CommonResult.ok(toiletBaseCount);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getToiletBaseInfo() {
+        List<Map<String, String>> toiletBaseInfo = toiletBaseMapper.getToiletBaseInfo();
+        if (toiletBaseInfo.isEmpty()){
+            return CommonResult.ok(toiletBaseInfo);
+        }
+        return CommonResult.ok(toiletBaseInfo);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getToiletRealTime() {
+        RestTemplate client = new RestTemplate();
+        List<Map<String, String>> toiletBaseInfo = toiletBaseMapper.getToiletBaseInfo();
+        int ToiletCount=toiletBaseInfo.size();
+        int intoNum=0;
+        if(!toiletBaseInfo.isEmpty()){
+            for (Map<String, String> infoMap:toiletBaseInfo) {
+                String id=String.valueOf(infoMap.get("id"));
+                ResponseEntity<String> responseEntity = client.getForEntity(url+id, String.class);
+                String body = responseEntity.getBody();
+                if (!responseEntity.getStatusCode().is2xxSuccessful()) {
+                    continue;
+                }
+                if ("false".equals(JSONObject.parseObject(body).getString("success"))) {
+                    return CommonResult.fail("请求实时数据异常:"+JSONObject.parseObject(body).getString("message"));
+                }
+                JSONObject jsonObject=JSONObject.parseObject(body).getJSONObject("data");
+                //入流量
+                int dataOfMan=jsonObject.getJSONObject("dataOfMan").getInteger("intoNum");
+                int dataOfWoman=jsonObject.getJSONObject("dataOfWoman").getInteger("intoNum");
+                int dataOfThird=jsonObject.getJSONObject("dataOfThird").getInteger("intoNum");
+                intoNum=intoNum+dataOfMan+dataOfWoman+dataOfThird;
+            }
+        }
+        Map<String, Object> resultMap=new HashMap<>();
+        resultMap.put("ToiletCount",ToiletCount);
+       Long intoNumTotal= toiletBaseMapper.getToiletBaseInfoHis();
+        resultMap.put("intoNumTotal",intoNumTotal);
+        resultMap.put("intoNum",intoNum);
+        return CommonResult.ok(resultMap);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getToiletRealTimeById(String toiletId) {
+        if("".equals(toiletId)){
+            return CommonResult.fail("请求厕所实时数据toiletId不能为空");
+        }
+        RestTemplate client = new RestTemplate();
+        ResponseEntity<String> responseEntity = client.getForEntity(url+toiletId, String.class);
+        String body = responseEntity.getBody();
+        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
+            return CommonResult.fail("请求厕所实时数据异常");
+        }
+        if ("false".equals(JSONObject.parseObject(body).getString("success"))) {
+            return CommonResult.fail("请求实时数据异常:"+JSONObject.parseObject(body).getString("message"));
+        }
+        JSONObject jsonObject=JSONObject.parseObject(body).getJSONObject("data");
+        return CommonResult.ok(jsonObject);
+    }
+}
+

+ 60 - 60
src/main/java/com/template/controller/WarmSmokeController.java

@@ -1,60 +1,60 @@
-package com.template.controller;
-
-
-import com.alibaba.fastjson.JSONObject;
-import com.template.annotation.PassToken;
-import com.template.api.ToiletBaseControllerAPI;
-import com.template.api.WarmSmokeControllerAPI;
-import com.template.mapper.ToiletBaseMapper;
-import com.template.mapper.WarmSmokeMapper;
-import com.template.model.result.CommonResult;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestTemplate;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- *  前端控制器
- * </p>
- *
- * @author ceshi
- * @since 2023-03-30
- */
-@RestController
-public class WarmSmokeController implements WarmSmokeControllerAPI {
-
-
-    @Value("${diseaseRightUrl}")
-    String url;
-
-    @Autowired
-    private WarmSmokeMapper warmSmokeMapper;
-
-
-    @Override
-    @PassToken
-    public CommonResult getWarmSmokeByPlace(String place) {
-        List<Map<String, String>> warmSmokeByPlace = warmSmokeMapper.getWarmSmokeByPlace(place);
-        if (warmSmokeByPlace.isEmpty()){
-            return CommonResult.ok("查询为空",warmSmokeByPlace);
-        }
-        return CommonResult.ok(warmSmokeByPlace);
-    }
-
-    @Override
-    @PassToken
-    public CommonResult getWarmSmokeCount() {
-        List<Map<String, String>> warmSmokeCount = warmSmokeMapper.getWarmSmokeCount();
-        if (warmSmokeCount.isEmpty()){
-            return CommonResult.ok("查询为空",warmSmokeCount);
-        }
-        return CommonResult.ok(warmSmokeCount);
-    }
-}
-
+package com.template.controller;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.template.annotation.PassToken;
+import com.template.api.ToiletBaseControllerAPI;
+import com.template.api.WarmSmokeControllerAPI;
+import com.template.mapper.ToiletBaseMapper;
+import com.template.mapper.WarmSmokeMapper;
+import com.template.model.result.CommonResult;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>
+ *  前端控制器
+ * </p>
+ *
+ * @author ceshi
+ * @since 2023-03-30
+ */
+@RestController
+public class WarmSmokeController implements WarmSmokeControllerAPI {
+
+
+    @Value("${diseaseRightUrl}")
+    String url;
+
+    @Autowired
+    private WarmSmokeMapper warmSmokeMapper;
+
+
+    @Override
+    @PassToken
+    public CommonResult getWarmSmokeByPlace(String place) {
+        List<Map<String, String>> warmSmokeByPlace = warmSmokeMapper.getWarmSmokeByPlace(place);
+        if (warmSmokeByPlace.isEmpty()){
+            return CommonResult.ok("查询为空",warmSmokeByPlace);
+        }
+        return CommonResult.ok(warmSmokeByPlace);
+    }
+
+    @Override
+    @PassToken
+    public CommonResult getWarmSmokeCount() {
+        List<Map<String, String>> warmSmokeCount = warmSmokeMapper.getWarmSmokeCount();
+        if (warmSmokeCount.isEmpty()){
+            return CommonResult.ok("查询为空",warmSmokeCount);
+        }
+        return CommonResult.ok(warmSmokeCount);
+    }
+}
+

+ 27 - 27
src/main/java/com/template/core/CORSConfiguration.java

@@ -1,27 +1,27 @@
-package com.template.core;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.CorsRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-@Configuration
-public class CORSConfiguration{
-    @Bean
-    public WebMvcConfigurer corsConfigurer() {
-        return new WebMvcConfigurer() {
-            @Override
-            public void addCorsMappings(CorsRegistry registry) {
-                registry.addMapping("/**")
-                        //放行哪些原始域
-                        .allowedOrigins("*")
-                        //是否发送Cookie信息
-                        .allowCredentials(false)
-                        //放行哪些原始域(请求方式)
-                        .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
-                        //放行哪些原始域(头部信息)
-                        .allowedHeaders("*");
-            }
-        };
-    }
-}
+package com.template.core;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class CORSConfiguration{
+    @Bean
+    public WebMvcConfigurer corsConfigurer() {
+        return new WebMvcConfigurer() {
+            @Override
+            public void addCorsMappings(CorsRegistry registry) {
+                registry.addMapping("/**")
+                        //放行哪些原始域
+                        .allowedOrigins("*")
+                        //是否发送Cookie信息
+                        .allowCredentials(false)
+                        //放行哪些原始域(请求方式)
+                        .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
+                        //放行哪些原始域(头部信息)
+                        .allowedHeaders("*");
+            }
+        };
+    }
+}

+ 113 - 113
src/main/java/com/template/core/JwtAuthenticationInterceptor.java

@@ -1,113 +1,113 @@
-package com.template.core;
-
-import com.auth0.jwt.interfaces.Claim;
-import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
-import com.template.annotation.PassToken;
-import com.template.common.exception.MyCustomException;
-import com.template.common.result.ResponseStatusEnum;
-import com.template.common.utils.JWTUtil;
-import org.springframework.boot.configurationprocessor.json.JSONObject;
-import org.springframework.util.StringUtils;
-import org.springframework.web.method.HandlerMethod;
-import org.springframework.web.servlet.HandlerInterceptor;
-import org.springframework.web.servlet.ModelAndView;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.PrintWriter;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-public class JwtAuthenticationInterceptor implements HandlerInterceptor {
-
-    /**
-     * preHandle:进入到控制器方法之前执行的内容
-     *     boolean:
-     *         true:可以继续执行控制器方法
-     *         false:拦截
-     * posthandler:执行控制器方法之后执行的内容
-     * afterCompletion:响应结束之前执行的内容
-     *///说明
-    @Override
-    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-
-        //region 检查是否有passtoken注释,有则跳过认证
-        //PassToken注解用在方法上面
-        HandlerMethod handlerMethod = (HandlerMethod) handler;
-        Method method = handlerMethod.getMethod();
-        if (method.isAnnotationPresent(PassToken.class)) {
-            PassToken passToken = method.getAnnotation(PassToken.class);
-            if (passToken.requeired()) {
-                return true;
-            }
-        }
-        //endregion
-
-        //除了登录和注册接口不需要user_head和token请求头外其他时候基本都要请求头
-        if(request.getHeader("user_head") == null){
-            //region 自定义返回响应的json格式
-            //加上这个可以让浏览器那里得到浏览器的401:response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-            response.setCharacterEncoding("UTF-8");
-            response.setContentType("application/json; charset=utf-8");
-            JSONObject res = new JSONObject();
-            res.put("code", ResponseStatusEnum.MISSING_REQUEST_HEADER.getStatus());
-            res.put("message",  ResponseStatusEnum.MISSING_REQUEST_HEADER.getMsg());
-            res.put("success", false);
-            PrintWriter out = null;
-            out = response.getWriter();
-            out.write(res.toString());
-            out.flush();
-            out.close();
-            //endregion
-            return false;
-        }
-
-        //region 获取url传递的参数 Query string传递的参数
-        //获取url参数 getParameter方法里的参数名和定义的参数名一致
-        String token = request.getHeader("token");
-        // 验证userToken
-        if (!StringUtils.hasText(token)) {
-            throw new MyCustomException(ResponseStatusEnum.SYSTEM_TOKEN_ERROR);
-        }
-
-        // 解析token
-        Map<String, Claim> stringClaimMap = JWTUtil.verifyToken(token);
-        if (ObjectUtils.isNotEmpty(stringClaimMap)) { // 登录
-            return true;
-        }
-        //endregion
-
-        //region 自定义返回响应的json格式
-        //加上这个可以让浏览器那里得到浏览器的401:response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-        response.setCharacterEncoding("UTF-8");
-        response.setContentType("application/json; charset=utf-8");
-        JSONObject res = new JSONObject();
-        res.put("code", ResponseStatusEnum.NO_PERMISSION.getStatus());
-        res.put("message", ResponseStatusEnum.NO_PERMISSION.getMsg());
-        res.put("success", false);
-        PrintWriter out = null;
-        out = response.getWriter();
-        out.write(res.toString());
-        out.flush();
-        out.close();
-        //endregion
-
-        //region 默认的响应提示信息
-        //上面的提示信息返回格式和下面的只能开启一个,否则应用日志系统会导致Idean抛出异常:
-        //java.lang.IllegalStateException: getWriter() has already been called for this response
-        //response.sendError(401, "无权限");
-        //endregion
-
-        return false;
-    }
-
-    @Override
-    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
-
-    }
-
-    @Override
-    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
-
-    }
-}
+package com.template.core;
+
+import com.auth0.jwt.interfaces.Claim;
+import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
+import com.template.annotation.PassToken;
+import com.template.common.exception.MyCustomException;
+import com.template.common.result.ResponseStatusEnum;
+import com.template.common.utils.JWTUtil;
+import org.springframework.boot.configurationprocessor.json.JSONObject;
+import org.springframework.util.StringUtils;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class JwtAuthenticationInterceptor implements HandlerInterceptor {
+
+    /**
+     * preHandle:进入到控制器方法之前执行的内容
+     *     boolean:
+     *         true:可以继续执行控制器方法
+     *         false:拦截
+     * posthandler:执行控制器方法之后执行的内容
+     * afterCompletion:响应结束之前执行的内容
+     *///说明
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+
+        //region 检查是否有passtoken注释,有则跳过认证
+        //PassToken注解用在方法上面
+        HandlerMethod handlerMethod = (HandlerMethod) handler;
+        Method method = handlerMethod.getMethod();
+        if (method.isAnnotationPresent(PassToken.class)) {
+            PassToken passToken = method.getAnnotation(PassToken.class);
+            if (passToken.requeired()) {
+                return true;
+            }
+        }
+        //endregion
+
+        //除了登录和注册接口不需要user_head和token请求头外其他时候基本都要请求头
+        if(request.getHeader("user_head") == null){
+            //region 自定义返回响应的json格式
+            //加上这个可以让浏览器那里得到浏览器的401:response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+            response.setCharacterEncoding("UTF-8");
+            response.setContentType("application/json; charset=utf-8");
+            JSONObject res = new JSONObject();
+            res.put("code", ResponseStatusEnum.MISSING_REQUEST_HEADER.getStatus());
+            res.put("message",  ResponseStatusEnum.MISSING_REQUEST_HEADER.getMsg());
+            res.put("success", false);
+            PrintWriter out = null;
+            out = response.getWriter();
+            out.write(res.toString());
+            out.flush();
+            out.close();
+            //endregion
+            return false;
+        }
+
+        //region 获取url传递的参数 Query string传递的参数
+        //获取url参数 getParameter方法里的参数名和定义的参数名一致
+        String token = request.getHeader("token");
+        // 验证userToken
+        if (!StringUtils.hasText(token)) {
+            throw new MyCustomException(ResponseStatusEnum.SYSTEM_TOKEN_ERROR);
+        }
+
+        // 解析token
+        Map<String, Claim> stringClaimMap = JWTUtil.verifyToken(token);
+        if (ObjectUtils.isNotEmpty(stringClaimMap)) { // 登录
+            return true;
+        }
+        //endregion
+
+        //region 自定义返回响应的json格式
+        //加上这个可以让浏览器那里得到浏览器的401:response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        response.setCharacterEncoding("UTF-8");
+        response.setContentType("application/json; charset=utf-8");
+        JSONObject res = new JSONObject();
+        res.put("code", ResponseStatusEnum.NO_PERMISSION.getStatus());
+        res.put("message", ResponseStatusEnum.NO_PERMISSION.getMsg());
+        res.put("success", false);
+        PrintWriter out = null;
+        out = response.getWriter();
+        out.write(res.toString());
+        out.flush();
+        out.close();
+        //endregion
+
+        //region 默认的响应提示信息
+        //上面的提示信息返回格式和下面的只能开启一个,否则应用日志系统会导致Idean抛出异常:
+        //java.lang.IllegalStateException: getWriter() has already been called for this response
+        //response.sendError(401, "无权限");
+        //endregion
+
+        return false;
+    }
+
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+
+    }
+}

+ 25 - 25
src/main/java/com/template/core/JwtlnterceptorConfig.java

@@ -1,25 +1,25 @@
-package com.template.core;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.HandlerInterceptor;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-@Configuration
-public class JwtlnterceptorConfig implements WebMvcConfigurer {
-    @Override
-    public void addInterceptors(InterceptorRegistry registry) {
-        //region
-        //目前测试下来 使用 /**所有的话,response.sendError浏览器获取不到响应的信息
-        //默认拦截所有路径
-        registry.addInterceptor(authenticationInterceptor())
-                .addPathPatterns("/api/**");
-        //endregion
-    }
-
-    @Bean
-    public HandlerInterceptor authenticationInterceptor() {
-        return new JwtAuthenticationInterceptor();
-    }
-}
+package com.template.core;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class JwtlnterceptorConfig implements WebMvcConfigurer {
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        //region
+        //目前测试下来 使用 /**所有的话,response.sendError浏览器获取不到响应的信息
+        //默认拦截所有路径
+        registry.addInterceptor(authenticationInterceptor())
+                .addPathPatterns("/api/**");
+        //endregion
+    }
+
+    @Bean
+    public HandlerInterceptor authenticationInterceptor() {
+        return new JwtAuthenticationInterceptor();
+    }
+}

+ 74 - 74
src/main/java/com/template/core/SwaggerConfiguration.java

@@ -1,74 +1,74 @@
-package com.template.core;
-
-import com.google.common.base.Predicates;
-import com.template.annotation.ControllerIsShow;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.builders.RequestHandlerSelectors;
-import springfox.documentation.service.ApiInfo;
-import springfox.documentation.service.Contact;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-@Configuration//配置对象
-@EnableSwagger2//声明启动Swagger2
-/*
-* 两种方式控制生产环境是否显示swagger
-* */
-//@Profile("!prod")
-@Profile({"dev","test"})
-public class SwaggerConfiguration {
-    /**
-     * 创建Docket类型的对象。并使用spring容器管理。
-     * Docket是Swagger中的全局配置对象。
-     * 请求方式:http://ip地址:端口/项目名/swagger-ui.html#/
-     */
-    @Bean
-    public Docket createRestApi() {
-        ApiInfo apiInfo = new ApiInfoBuilder()
-                .version("1.1.0") //版本
-                .title("视频系统接口文档") //网站标题
-                .description("提供测试接口或前端查看对应参数以及返回参数使用") //网站描述
-                .contact(new Contact("创海", "https://www.baidu.com/", "a974264710@163.com"))
-                //region 在swagger中显示作用不是很大
-                /*
-                .license("The Apache License") //协议
-                .licenseUrl("http://www.baidu.com") //许可证链接地址
-                */
-                //endregion
-                .build();
-
-        return new Docket(DocumentationType.SWAGGER_2)
-                .apiInfo(apiInfo)//参数为类对象,并且这个类对象是swagger版本
-                .select()//获取Docket中的选择器。返回ApiSelctorBuilder。构建选择器的。如:扫描什么包的注解。
-                .apis(
-                        //region 是否在swagger中进行展示对应控制器
-                        /*
-                         Predicates.not:取反 例如,false -> true
-                         withMethodAnnotation:当方法上有注解的时候返回true
-                         整体作用:启用该段代码之后如果在方法上使用的自定义的注解:ControllerIsShow
-                         则在swagger中不会显示该方法
-                        */
-                        Predicates.not(
-                                RequestHandlerSelectors.withMethodAnnotation(
-                                        ControllerIsShow.class
-                                )
-                        )
-                        //endregion
-                )
-                .apis(RequestHandlerSelectors.basePackage("com.video"))//设定扫描哪个包(包含子包)中的注解。 如果要匹配多个不同包下的控制器可以精确到多个包的统一父级
-                //region 匹配路由地址
-                /*
-                //用正则匹配显示路由地址为swagger开头的链接 即:范围匹配器 以此来控制在swagger中描述哪些控制器
-                .paths(
-                        PathSelectors.regex("/swagger/.*")
-                )
-                */
-                //endregion
-                .build();//重新构建Docket对象
-
-    }
-}
+package com.template.core;
+
+import com.google.common.base.Predicates;
+import com.template.annotation.ControllerIsShow;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@Configuration//配置对象
+@EnableSwagger2//声明启动Swagger2
+/*
+* 两种方式控制生产环境是否显示swagger
+* */
+//@Profile("!prod")
+@Profile({"dev","test"})
+public class SwaggerConfiguration {
+    /**
+     * 创建Docket类型的对象。并使用spring容器管理。
+     * Docket是Swagger中的全局配置对象。
+     * 请求方式:http://ip地址:端口/项目名/swagger-ui.html#/
+     */
+    @Bean
+    public Docket createRestApi() {
+        ApiInfo apiInfo = new ApiInfoBuilder()
+                .version("1.1.0") //版本
+                .title("视频系统接口文档") //网站标题
+                .description("提供测试接口或前端查看对应参数以及返回参数使用") //网站描述
+                .contact(new Contact("创海", "https://www.baidu.com/", "a974264710@163.com"))
+                //region 在swagger中显示作用不是很大
+                /*
+                .license("The Apache License") //协议
+                .licenseUrl("http://www.baidu.com") //许可证链接地址
+                */
+                //endregion
+                .build();
+
+        return new Docket(DocumentationType.SWAGGER_2)
+                .apiInfo(apiInfo)//参数为类对象,并且这个类对象是swagger版本
+                .select()//获取Docket中的选择器。返回ApiSelctorBuilder。构建选择器的。如:扫描什么包的注解。
+                .apis(
+                        //region 是否在swagger中进行展示对应控制器
+                        /*
+                         Predicates.not:取反 例如,false -> true
+                         withMethodAnnotation:当方法上有注解的时候返回true
+                         整体作用:启用该段代码之后如果在方法上使用的自定义的注解:ControllerIsShow
+                         则在swagger中不会显示该方法
+                        */
+                        Predicates.not(
+                                RequestHandlerSelectors.withMethodAnnotation(
+                                        ControllerIsShow.class
+                                )
+                        )
+                        //endregion
+                )
+                .apis(RequestHandlerSelectors.basePackage("com.video"))//设定扫描哪个包(包含子包)中的注解。 如果要匹配多个不同包下的控制器可以精确到多个包的统一父级
+                //region 匹配路由地址
+                /*
+                //用正则匹配显示路由地址为swagger开头的链接 即:范围匹配器 以此来控制在swagger中描述哪些控制器
+                .paths(
+                        PathSelectors.regex("/swagger/.*")
+                )
+                */
+                //endregion
+                .build();//重新构建Docket对象
+
+    }
+}

+ 26 - 26
src/main/java/com/template/handle/NonStaticResourceHttpRequestHandler.java

@@ -1,26 +1,26 @@
-package com.template.handle;
-
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.core.io.Resource;
-import org.springframework.stereotype.Component;
-import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
-
-import javax.servlet.http.HttpServletRequest;
-import java.nio.file.Path;
-
-/**
- * @Author: binguo
- * @Date: 2023/3/27 星期一 8:49
- * @Description: com.video.handle
- * @Version: 1.0
- */
-@Component
-public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {
-    public final static String ATTR_FILE = "NON-STATIC-FILE";
-
-    @Override
-    protected Resource getResource(HttpServletRequest request) {
-        final Path filePath = (Path) request.getAttribute(ATTR_FILE);
-        return new FileSystemResource(filePath);
-    }
-}
+package com.template.handle;
+
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
+
+import javax.servlet.http.HttpServletRequest;
+import java.nio.file.Path;
+
+/**
+ * @Author: binguo
+ * @Date: 2023/3/27 星期一 8:49
+ * @Description: com.video.handle
+ * @Version: 1.0
+ */
+@Component
+public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {
+    public final static String ATTR_FILE = "NON-STATIC-FILE";
+
+    @Override
+    protected Resource getResource(HttpServletRequest request) {
+        final Path filePath = (Path) request.getAttribute(ATTR_FILE);
+        return new FileSystemResource(filePath);
+    }
+}

+ 60 - 60
src/main/java/com/template/handler/MyMetaObjectHandler.java

@@ -1,60 +1,60 @@
-package com.template.handler;
-
-import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
-import com.template.common.utils.AesUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.ibatis.reflection.MetaObject;
-import org.springframework.stereotype.Component;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.Date;
-
-@Slf4j
-@Component // 一定不要忘记把处理器加到IOC容器中!
-public class MyMetaObjectHandler implements MetaObjectHandler {
-    //创建用户和更新用户填充0的时候则说明不是账号操作的
-
-    // 插入时的填充策略
-    @Override
-    public void insertFill(MetaObject metaObject) {
-        HttpServletRequest request = getHttpServletRequest();
-        if (request != null) {
-            String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
-            log.info("start insert fill.....");
-            // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
-            this.setFieldValByName("createTime", new Date(), metaObject);
-            this.setFieldValByName("updateTime", new Date(), metaObject);
-            this.setFieldValByName("createUser", user_id, metaObject);
-            this.setFieldValByName("updateUser", user_id, metaObject);
-            this.setFieldValByName("deleted", 0, metaObject);
-        } else {
-            this.setFieldValByName("createTime", new Date(), metaObject);
-            this.setFieldValByName("updateTime", new Date(), metaObject);
-            this.setFieldValByName("createUser","0", metaObject);
-            this.setFieldValByName("updateUser","0", metaObject);
-            this.setFieldValByName("deleted", 0, metaObject);
-        }
-    }
-
-    // 更新时的填充策略
-    @Override
-    public void updateFill(MetaObject metaObject) {
-        HttpServletRequest request = getHttpServletRequest();
-        if (request != null) {
-            String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
-            log.info("start update fill.....");
-            this.setFieldValByName("updateTime", new Date(), metaObject);
-            this.setFieldValByName("updateUser", user_id, metaObject);
-        }
-
-    }
-
-    private HttpServletRequest getHttpServletRequest() {
-        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
-        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
-        return attributes == null ? null : attributes.getRequest();
-    }
-}
+package com.template.handler;
+
+import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
+import com.template.common.utils.AesUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.ibatis.reflection.MetaObject;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestAttributes;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Date;
+
+@Slf4j
+@Component // 一定不要忘记把处理器加到IOC容器中!
+public class MyMetaObjectHandler implements MetaObjectHandler {
+    //创建用户和更新用户填充0的时候则说明不是账号操作的
+
+    // 插入时的填充策略
+    @Override
+    public void insertFill(MetaObject metaObject) {
+        HttpServletRequest request = getHttpServletRequest();
+        if (request != null) {
+            String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
+            log.info("start insert fill.....");
+            // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
+            this.setFieldValByName("createTime", new Date(), metaObject);
+            this.setFieldValByName("updateTime", new Date(), metaObject);
+            this.setFieldValByName("createUser", user_id, metaObject);
+            this.setFieldValByName("updateUser", user_id, metaObject);
+            this.setFieldValByName("deleted", 0, metaObject);
+        } else {
+            this.setFieldValByName("createTime", new Date(), metaObject);
+            this.setFieldValByName("updateTime", new Date(), metaObject);
+            this.setFieldValByName("createUser","0", metaObject);
+            this.setFieldValByName("updateUser","0", metaObject);
+            this.setFieldValByName("deleted", 0, metaObject);
+        }
+    }
+
+    // 更新时的填充策略
+    @Override
+    public void updateFill(MetaObject metaObject) {
+        HttpServletRequest request = getHttpServletRequest();
+        if (request != null) {
+            String user_id = request.getHeader("user_head") == null ? "0" : AesUtils.decrypt(request.getHeader("user_head"));
+            log.info("start update fill.....");
+            this.setFieldValByName("updateTime", new Date(), metaObject);
+            this.setFieldValByName("updateUser", user_id, metaObject);
+        }
+
+    }
+
+    private HttpServletRequest getHttpServletRequest() {
+        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
+        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
+        return attributes == null ? null : attributes.getRequest();
+    }
+}

+ 93 - 93
src/main/java/com/template/mapper/BookingMapper.java

@@ -1,93 +1,93 @@
-package com.template.mapper;
-
-
-import org.apache.ibatis.annotations.Delete;
-import org.apache.ibatis.annotations.Mapper;
-import org.apache.ibatis.annotations.Param;
-import org.apache.ibatis.annotations.Select;
-import org.springframework.stereotype.Repository;
-
-import java.util.List;
-import java.util.Map;
-
-@Repository
-@Mapper
-public interface BookingMapper {
-
-    @Select("insert into booking (id,order_num,user_name,hotel_id,house_unit_price,order_start_time,order_end_time,order_live_time) values \n" +
-            "(uuid(),#{booking.orderId},#{booking.name},#{booking.hotalId},#{booking.price},#{booking.startTime},#{booking.endTime},'1')")
-    Integer insertBooking(@Param("booking") Map<String,String> booking);
-
-    @Select("select  username from repair_admin ra order by rand() limit 1")
-    List<Map<String,String>> getRandName();
-
-    @Select("select  count(1) count,sum(house_unit_price) value from booking b ")
-    List<Map<String,String>> getTotal();
-
-    @Select("SELECT  COUNT(1) COUNT,SUM(house_unit_price) VALUE FROM booking b WHERE \n" +
-            "            create_time>=DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY)\n" +
-            "            AND create_time<CURRENT_DATE()")
-    List<Map<String,String>> getYestedayTotal();
-
-    @Select("select   left(order_end_time,10) endtime,count(1) total from booking b \n" +
-            "where create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
-            "group by order_end_time  ")
-    List<Map<String,String>> get7Trend();
-
-    @Select("select hotel_id hotelid ,h.hname,count(1) total from booking b,hotel h where b.hotel_id =h.id \n" +
-            "and create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
-            "group by hotel_id order by count(1) desc")
-    List<Map<String,String>> getRank();
-
-
-    @Select("select  left(order_end_time,10) endtime,round(avg(house_unit_price),2) priceavg from booking b \n" +
-            "where create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
-            "group by order_end_time ")
-    List<Map<String,String>> get7Avg();
-
-    @Select("select concat(round(avg(score)/5*100,2),'%') scoreavg from booking_comment ")
-    List<Map<String,String>> getCommentAvg();
-
-    @Select({"<script>"+
-            "select count(1) from booking_comment  where 1=1 "+
-            " <if test='name != null and name != \"\"'>"+
-            " and comment_name like '%${name}%' "+
-            " </if>"+
-            " <if test='startTime != null and startTime != \"\"'>"+
-            "and create_date>=#{startTime}"+
-            " </if>"+
-//            " <if test='endTime != null and endTime != \"\"'>"+
-//            "and  create_date < #{endTime}"+
-//            " </if>"+
-            " <if test='endTime != null and endTime != \"\"'>"+
-            "and #{endTime} >= create_date"+
-            " </if>"+
-            " <if test='flag != null and flag != \"\"'>"+
-            "and  comment_status = #{flag}"+
-            " </if>"+
-            "</script>"})
-    int getCommentInfoTotal(@Param("name")String name,@Param("startTime")String startTime,@Param("endTime")String endTime,
-                                            @Param("flag")String flag);
-
-    @Select({"<script>"+
-            "select comment_name, booking_id,content,score,create_date,comment_status,create_id photo from booking_comment where 1=1 "+
-            " <if test='name != null and name != \"\"'>"+
-            " and comment_name like '%${name}%' "+
-            " </if>"+
-            " <if test='startTime != null and startTime != \"\"'>"+
-            "and create_date>=#{startTime}"+
-            " </if>"+
-//            " <if test='endTime != null and endTime != \"\"'>"+
-//            "and  create_date < #{endTime}"+
-//            " </if>"+
-            " <if test='endTime != null and endTime != \"\"'>"+
-            "and #{endTime} >= create_date"+
-            " </if>"+
-            " <if test='flag != null and flag != \"\"'>"+
-            "and  comment_status = #{flag}"+
-            " </if>"+
-            "limit #{pageIndex},#{pageSize}"+
-            "</script>"})
-    List<Map<String,String>> getCommentInfo(@Param("name")String name,@Param("startTime")String startTime,@Param("endTime")String endTime,
-                                            @Param("flag")String flag,@Param("pageIndex")int pageIndex,@Param("pageSize")int pageSize);
-}
+package com.template.mapper;
+
+
+import org.apache.ibatis.annotations.Delete;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+import java.util.Map;
+
+@Repository
+@Mapper
+public interface BookingMapper {
+
+    @Select("insert into booking (id,order_num,user_name,hotel_id,house_unit_price,order_start_time,order_end_time,order_live_time) values \n" +
+            "(uuid(),#{booking.orderId},#{booking.name},#{booking.hotalId},#{booking.price},#{booking.startTime},#{booking.endTime},'1')")
+    Integer insertBooking(@Param("booking") Map<String,String> booking);
+
+    @Select("select  username from repair_admin ra order by rand() limit 1")
+    List<Map<String,String>> getRandName();
+
+    @Select("select  count(1) count,sum(house_unit_price) value from booking b ")
+    List<Map<String,String>> getTotal();
+
+    @Select("SELECT  COUNT(1) COUNT,SUM(house_unit_price) VALUE FROM booking b WHERE \n" +
+            "            create_time>=DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY)\n" +
+            "            AND create_time<CURRENT_DATE()")
+    List<Map<String,String>> getYestedayTotal();
+
+    @Select("select   left(order_end_time,10) endtime,count(1) total from booking b \n" +
+            "where create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
+            "group by order_end_time  ")
+    List<Map<String,String>> get7Trend();
+
+    @Select("select hotel_id hotelid ,h.hname,count(1) total from booking b,hotel h where b.hotel_id =h.id \n" +
+            "and create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
+            "group by hotel_id order by count(1) desc")
+    List<Map<String,String>> getRank();
+
+
+    @Select("select  left(order_end_time,10) endtime,round(avg(house_unit_price),2) priceavg from booking b \n" +
+            "where create_time<current_date() and create_time>=date_sub(current_date(),interval 7 day) \n" +
+            "group by order_end_time ")
+    List<Map<String,String>> get7Avg();
+
+    @Select("select concat(round(avg(score)/5*100,2),'%') scoreavg from booking_comment ")
+    List<Map<String,String>> getCommentAvg();
+
+    @Select({"<script>"+
+            "select count(1) from booking_comment  where 1=1 "+
+            " <if test='name != null and name != \"\"'>"+
+            " and comment_name like '%${name}%' "+
+            " </if>"+
+            " <if test='startTime != null and startTime != \"\"'>"+
+            "and create_date>=#{startTime}"+
+            " </if>"+
+//            " <if test='endTime != null and endTime != \"\"'>"+
+//            "and  create_date < #{endTime}"+
+//            " </if>"+
+            " <if test='endTime != null and endTime != \"\"'>"+
+            "and #{endTime} >= create_date"+
+            " </if>"+
+            " <if test='flag != null and flag != \"\"'>"+
+            "and  comment_status = #{flag}"+
+            " </if>"+
+            "</script>"})
+    int getCommentInfoTotal(@Param("name")String name,@Param("startTime")String startTime,@Param("endTime")String endTime,
+                                            @Param("flag")String flag);
+
+    @Select({"<script>"+
+            "select comment_name, booking_id,content,score,create_date,comment_status,create_id photo from booking_comment where 1=1 "+
+            " <if test='name != null and name != \"\"'>"+
+            " and comment_name like '%${name}%' "+
+            " </if>"+
+            " <if test='startTime != null and startTime != \"\"'>"+
+            "and create_date>=#{startTime}"+
+            " </if>"+
+//            " <if test='endTime != null and endTime != \"\"'>"+
+//            "and  create_date < #{endTime}"+
+//            " </if>"+
+            " <if test='endTime != null and endTime != \"\"'>"+
+            "and #{endTime} >= create_date"+
+            " </if>"+
+            " <if test='flag != null and flag != \"\"'>"+
+            "and  comment_status = #{flag}"+
+            " </if>"+
+            "limit #{pageIndex},#{pageSize}"+
+            "</script>"})
+    List<Map<String,String>> getCommentInfo(@Param("name")String name,@Param("startTime")String startTime,@Param("endTime")String endTime,
+                                            @Param("flag")String flag,@Param("pageIndex")int pageIndex,@Param("pageSize")int pageSize);
+}

+ 55 - 55
src/main/java/com/template/mapper/HotelMapper.java

@@ -1,55 +1,55 @@
-package com.template.mapper;
-
-
-import org.apache.ibatis.annotations.Mapper;
-import org.apache.ibatis.annotations.Param;
-import org.apache.ibatis.annotations.Select;
-import org.springframework.stereotype.Repository;
-
-import java.util.List;
-import java.util.Map;
-
-@Repository
-@Mapper
-public interface HotelMapper {
-
-
-    @Select("select hotel_level town,count(1) total  from hotel h group by hotel_level ")
-    List<Map<String,String>> getTownRate();
-
-    @Select({"<script>"+
-            "select count(1)  from hotel h where 1=1 "+
-            " <if test='town != null and town != \"\"'>"+
-            " and hotel_level =#{town} "+
-            " </if>"+
-            " <if test='hName != null and hName != \"\"'>"+
-            "and  hname like '%${hName}%'"+
-            " </if>" +
-            "</script>"})
-    int getTownTotal(@Param("town") String town,@Param("hName") String hName);
-
-    @Select({"<script>"+
-            "select *  from hotel h where 1=1 "+
-            " <if test='town != null and town != \"\"'>"+
-            " and hotel_level =#{town} "+
-            " </if>"+
-            " <if test='hName != null and hName != \"\"'>"+
-            "and  hname like '%${hName}%'"+
-            " </if>" +
-            "limit #{pageIndex},#{pageSize}"+
-            "</script>"})
-    List<Map<String,Object>> getHotelList(@Param("town") String town,@Param("hName") String hName,@Param("pageIndex")int pageIndex,@Param("pageSize")int pageSize);
-
-    @Select({"<script>"+
-            "select *  from hotel h where 1=1 "+
-
-            " <if test='hName != null and hName != \"\"'>"+
-            "and  hname like '%${hName}%'"+
-            " </if>" +
-            " <if test='hName == \"\"'>"+
-            "and  hname = ''"+
-            " </if>" +
-            "</script>"})
-    List<Map<String,Object>> getHotelListByName(@Param("hName") String hName);
-
-}
+package com.template.mapper;
+
+
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+import java.util.Map;
+
+@Repository
+@Mapper
+public interface HotelMapper {
+
+
+    @Select("select hotel_level town,count(1) total  from hotel h group by hotel_level ")
+    List<Map<String,String>> getTownRate();
+
+    @Select({"<script>"+
+            "select count(1)  from hotel h where 1=1 "+
+            " <if test='town != null and town != \"\"'>"+
+            " and hotel_level =#{town} "+
+            " </if>"+
+            " <if test='hName != null and hName != \"\"'>"+
+            "and  hname like '%${hName}%'"+
+            " </if>" +
+            "</script>"})
+    int getTownTotal(@Param("town") String town,@Param("hName") String hName);
+
+    @Select({"<script>"+
+            "select *  from hotel h where 1=1 "+
+            " <if test='town != null and town != \"\"'>"+
+            " and hotel_level =#{town} "+
+            " </if>"+
+            " <if test='hName != null and hName != \"\"'>"+
+            "and  hname like '%${hName}%'"+
+            " </if>" +
+            "limit #{pageIndex},#{pageSize}"+
+            "</script>"})
+    List<Map<String,Object>> getHotelList(@Param("town") String town,@Param("hName") String hName,@Param("pageIndex")int pageIndex,@Param("pageSize")int pageSize);
+
+    @Select({"<script>"+
+            "select *  from hotel h where 1=1 "+
+
+            " <if test='hName != null and hName != \"\"'>"+
+            "and  hname like '%${hName}%'"+
+            " </if>" +
+            " <if test='hName == \"\"'>"+
+            "and  hname = ''"+
+            " </if>" +
+            "</script>"})
+    List<Map<String,Object>> getHotelListByName(@Param("hName") String hName);
+
+}

+ 0 - 0
src/main/java/com/template/mapper/ParkingMapper.java


Some files were not shown because too many files changed in this diff