java 当最后一个属性具有时,Sping Boot 中的GetMapping到方法不按要求工作,(点)

xlpyo6sf  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(99)

我正在使用Maven的SpringBoot来读取JSON文件,但是GetMapping没有按预期工作。
预期的URL是http://localhost:8081/TestResults,其中TestResults是提供的目录路径中的JSON文件[TestResults.json]。
目前,下面的代码只有在我将'.json'添加到GetMapping值时才有效。请帮助我了解我的代码有什么问题。

@GetMapping(path = "/{fileName}.json", produces = MediaType.APPLICATION_JSON_VALUE)

上面的代码迫使我使用URL http://localhost:8081/TestResults.json,这不是我想要的。
下面是我的完整代码:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

@SpringBootApplication
public class SssApplication {

    public static void main(String[] args) {
        SpringApplication.run(SssApplication.class, args);
    }

}

@RestController
class FileController {
    private final String directoryPath = "C:\\Users\\Hello\\Documents\\Demo";

    @GetMapping(path = "/{fileName}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getFile(@PathVariable String fileName) throws FileNotFoundException {
        System.out.println("fileName:" + fileName);
        System.out.flush(); // Flush the output to ensure it is displayed in the console

        String fullFileName = fileName.endsWith(".json") ? fileName : fileName + ".json";
        System.out.println("fullFileName:" + fullFileName);
        System.out.flush(); // Flush the output to ensure it is displayed in the console

        File file = findFileRecursively(new File(directoryPath), fullFileName);
        System.out.println("file:" + file);
        System.out.flush(); // Flush the output to ensure it is displayed in the console

        if (file != null && file.isFile()) {
            System.out.println("file:" + file);
            System.out.flush(); // Flush the output to ensure it is displayed in the console

            try {
                System.out.println("file toPath:" + file.toPath());
                System.out.flush(); // Flush the output to ensure it is displayed in the console
                byte[] fileContent = Files.readAllBytes(file.toPath());
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.setContentLength(fileContent.length);
                return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
            }
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File not found");
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile() {
        // Handle file upload logic here
        return ResponseEntity.ok().body("File upload successful");
    }

    private File findFileRecursively(File directory, String fileName) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().equalsIgnoreCase(fileName)) {
                    return file;
                } else if (file.isDirectory()) {
                    File foundFile = findFileRecursively(file, fileName);
                    if (foundFile != null) {
                        return foundFile;
                    }
                }
            }
        }
        return null;
    }
}

pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.version>3.8.1</maven.compiler.version>
    <spring-boot.version>2.5.2</spring-boot.version>
    <gson.version>2.8.7</gson.version>
</properties>
whitzsjs

whitzsjs1#

在Springboot中:

  1. URL example/first/second导致计算firstValue =“first”和secondValue =“second”
    1.当使用示例/gallery.df/second.ar URL时,我们将有firstValue =“first.df”和secondValue =“second”
    1.对于example/first.df/second.com.ar URL,我们的变量将是firstValue =“first.df”和secondValue =“second.com”
    我们可以看到,second总是被截断的。
    可能的解决方案:

使用正则表达式:

@GetMapping("/example/{firstValue}/{secondValue:.+}")

以斜杠结尾:

@GetMapping("/example/{firstValue}/{secondValue}/")

有关更多详细信息,请参阅refer

相关问题