浏览代码

feature 获取模板方式修改

xiahan 3 月之前
父节点
当前提交
cf7f934b58

+ 3 - 0
pom.xml

@@ -12,6 +12,9 @@
         <resources>
             <resource>
                 <directory>src/main/resources</directory>
+                <excludes>
+                    <exclude>temp/cjd/**</exclude>
+                </excludes>
                 <!-- 包含所有文件(默认行为) -->
                 <includes>
                     <include>**/*</include>

+ 2 - 3
zhsw-common/src/main/java/com/rongwei/zhsw/system/service/impl/SwCollectionNoticeServiceImpl.java

@@ -340,7 +340,7 @@ public class SwCollectionNoticeServiceImpl implements SwCollectionNoticeService
         List<SwBusinesshallDo> list = swBusinesshallService.list(new LambdaQueryWrapper<SwBusinesshallDo>().eq(BaseDo::getDeleted, "0")
                 .orderByAsc(SwBusinesshallDo::getOrdernumber));
         String addresStr = list.stream().map(data -> data.getAddress()+" ("+data.getWorktime()+")").collect(Collectors.joining("\n"));
-        try (InputStream templateStream = EnvironmentAwareResourceLoader.loadResource(tempName)) {
+        try (InputStream templateStream = EnvironmentAwareResourceLoader.loadResource("cjdTemp",tempName)) {
             Date now = new Date();
             Calendar instance = Calendar.getInstance();
             instance.setTime(now);
@@ -405,8 +405,7 @@ public class SwCollectionNoticeServiceImpl implements SwCollectionNoticeService
             // 保存合并后的 PDF
             mergedDoc.save(response.getOutputStream(), SaveFormat.PDF);
         } catch (Exception e) {
-            e.printStackTrace();
-            log.error("催缴单生成失败");
+            log.error("催缴单生成失败:{}",e.getMessage());
         }
 
     }

+ 62 - 36
zhsw-common/src/main/java/com/rongwei/zhsw/system/utils/EnvironmentAwareResourceLoader.java

@@ -1,12 +1,19 @@
 package com.rongwei.zhsw.system.utils;
 
+import com.rongwei.rwcommon.base.exception.CustomException;
+import com.rongwei.rwcommon.utils.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.boot.system.ApplicationHome;
 import org.springframework.core.io.ClassPathResource;
 
 import java.io.File;
-import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.URI;
 import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 
 /**
  * EnvironmentAwareResourceLoader class
@@ -15,6 +22,8 @@ import java.nio.file.Files;
  * @date 2025/05/06
  */
 public class EnvironmentAwareResourceLoader {
+    private static final Logger log = LoggerFactory.getLogger(EnvironmentAwareResourceLoader.class);
+
     /**
      * 智能加载资源(自动判断环境)
      *
@@ -22,60 +31,77 @@ public class EnvironmentAwareResourceLoader {
      * @return 文件输入流
      * @throws IOException
      */
-    public static InputStream loadResource(String relativePath) throws IOException {
-        if (isRunningInJar()) {
-            // 服务器环境:从JAR同级目录加载
-            File jarDir = getJarDirectory();
-            File targetFile = new File(jarDir, "cjdTemp/" + relativePath);
-
-            if (!targetFile.exists()) {
-                throw new FileNotFoundException("服务器环境文件未找到: " + targetFile.getAbsolutePath());
+    public static InputStream loadResource(String prefix,String relativePath) {
+        if(StringUtils.isBlank(prefix)){
+            log.error("模板路径前缀不能为空");
+            throw new CustomException("模板路径前缀不能为空");
+        }
+        try {
+            if (isRunningInJar()) {
+                Path jarDir = getJarDirectory();
+                Path targetPath = jarDir.resolve(prefix).resolve(relativePath).normalize().toRealPath();
+                log.debug("jarPath:{}", targetPath);
+                if (!targetPath.isAbsolute()) {
+                    throw new CustomException("路径必须为绝对路径: " + targetPath);
+                }
+                if (!Files.exists(targetPath)) {
+                    throw new CustomException("模板资源不存在: " + targetPath);
+                }
+                return Files.newInputStream(targetPath);
+            } else {
+                // 开发环境:从resources目录加载
+                ClassPathResource classPathResource = new ClassPathResource("temp/"+prefix+"/" + relativePath);
+                return classPathResource.getInputStream();
             }
-            return Files.newInputStream(targetFile.toPath());
-
-        } else {
-            // 开发环境:从resources目录加载
-            ClassPathResource classPathResource = new ClassPathResource("temp/cjd/" + relativePath);
-            return classPathResource.getInputStream();
+        } catch (Exception e) {
+            log.error("模板获取失败:{}",e.getMessage());
+            throw new CustomException("模板获取失败");
         }
     }
 
     /**
-     * 判断是否运行在JAR包中
+     * 安全获取JAR所在目录
      */
-    private static boolean isRunningInJar() {
+    private static Path getJarDirectory() {
+        try {
+            // 方案1:通过Spring Boot的ApplicationHome
+            ApplicationHome home = new ApplicationHome(EnvironmentAwareResourceLoader.class);
+            File jarFile = home.getSource();
+            if (jarFile != null) {
+                Path path = jarFile.getParentFile().toPath().toRealPath();
+                log.debug("通过ApplicationHome获取JAR目录: {}", path);
+                return path;
+            }
+        } catch (Exception e) {
+            log.warn("Spring Boot路径获取失败: {}", e.getMessage());
+        }
+
+        // 方案2:通用JAR路径获取
         try {
-            String path = EnvironmentAwareResourceLoader.class
+            URI jarUri = EnvironmentAwareResourceLoader.class
                     .getProtectionDomain()
                     .getCodeSource()
                     .getLocation()
-                    .toURI()
-                    .getPath();
+                    .toURI();
 
-            return path.contains(".jar!");
+            Path jarPath = Paths.get(jarUri).getParent();
+            log.debug("通过CodeSource获取JAR目录: {}", jarPath);
+            return jarPath.toRealPath();
         } catch (Exception e) {
-            return false; // 异常情况默认视为开发环境
+            throw new RuntimeException("无法确定JAR目录", e);
         }
     }
 
     /**
-     * 获取JAR所在目录(仅在JAR运行时有效)
+     * 判断是否运行在JAR包中
      */
-    private static File getJarDirectory() {
+    private static boolean isRunningInJar() {
         try {
-            String jarPath = EnvironmentAwareResourceLoader.class
-                    .getProtectionDomain()
-                    .getCodeSource()
-                    .getLocation()
-                    .toURI()
-                    .getPath();
-
-            String decodedPath = java.net.URLDecoder.decode(jarPath, String.valueOf(java.nio.charset.StandardCharsets.UTF_8));
-            File jarFile = new File(decodedPath);
-            return jarFile.getParentFile();
-
+            String path = EnvironmentAwareResourceLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI().getScheme();
+            log.debug("path:{}", path);
+            return path.equals("jar");
         } catch (Exception e) {
-            throw new RuntimeException("获取JAR路径失败", e);
+            return false; // 异常情况默认视为开发环境
         }
     }
 }

zhsw-server/src/main/resources/temp/cjd/徐州大吴水务催缴单.docx → zhsw-server/src/main/resources/temp/cjdTemp/徐州大吴水务催缴单.docx