首页 > 解决方案 > 无法使用 Spring Boot REST API、Thymeleaf 和 JS 获取显示文件的原始内容

问题描述

我有一个Spring Boot应用程序,它在加载主页 ( http://localhost:8080) 时成功显示浏览器上特定目录中的所有文件名,没有任何问题。

现在,我想让这些文件名成为一个超链接,单击它会在浏览器上显示该文件的内容。

这样做时出现JS错误。该请求甚至没有到达服务器。我调用函数并在其中传递文件名参数的方式有问题吗?

错误:

VM164:1 Uncaught ReferenceError: database.properties is not defined
at <anonymous>:1:17

家庭控制器.java

@Controller
public class HomeController {
    @GetMapping({"", "/", "/home"})
    public String index(Model model) {
        return "home";
    }
}

目录列表控制器.java

@RestController
public class DirListController {

    @Autowired
    private SshConnService sshConnService;

    @GetMapping("/api/dir")
    public List<String> showAllDirs(Model model) throws Exception {
        return sshConnService.listAllFiles(); //returns [database.properties, messaging.properties, ....]
    }

}

RawFileContentController.java

@RestController
public class RawFileContentController {

    @Autowired
    private SshConnService sshConnService;

    @GetMapping("/api/rawFileContent")
    public String showRawFileContent(@RequestParam(value = "filename") String filename) throws Exception {
        return sshConnService.catFile(filename);
    }

}

主页.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Directory List</title>
    </head>
    <body>
        <h1>Directory List</h1>
        <table id="categoryTable" class="table" style="margin-top:10px;">
            <thead>
                <tr>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <h2>File Contents</h2>
        <table id="contentTable" class="table" style="margin-top:10px;">
            <thead>
                <tr>
                    <th>File Content</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <script src="/webjars/jquery/3.0.0/jquery.min.js"></script>
        <script src="/js/main.js"></script>
    </body>
</html>

js/main.js

$(document).ready(function () {
    viewAllDirs();
});


/*** Show all files within a directory **/
async function viewAllDirs() {
    $('#categoryTable tbody').empty();
    const dirResponse = await dirService.findAll();
    const dirJson = dirResponse.json();
    dirJson.then(filename => {
        filename.forEach(filename => {
            console.log(filename);
            //make the filename clickable and display it's content onclick
            let categoryRow = `$(<tr><td><a href="javascript:viewFileContent(${filename})">${filename}</a></td></tr>)`;
            $('#categoryTable tbody').append(categoryRow);
        });
    });
}

const dirService = {
    findAll: async () => {
        return await fetch('/api/dir');
    }
};



/*** View File Contents **/
async function viewFileContent(filename) {
    $('#contentTable tbody').empty();
    const rawFileContentResponse = await rawFileContentService.findByFilename(filename);
    const rawFileContentResponseJson = rawFileContentResponse.json();
    console.log(rawFileContentResponseJson);
    let contentRow = `$(<tr><td>${rawFileContentResponseJson}</td></tr>)`;
    $('#contentTable tbody').append(contentRow);
}

const rawFileContentService = {
    findByFilename: async (filename) => {
        return await fetch('/api/rawFileContent?filename=' + filename);
    }
};

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.1.3</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>font-awesome</artifactId>
    <version>5.8.2</version>
</dependency>

标签: javascriptjavaspringspring-bootfetch-api

解决方案


推荐阅读