随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

这一步的目标是把目录中的文件展示到前台。

创建一个IndexController

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }

}

意图很明显,就是为了返回一个叫做index的页面。

但是,我们现在还没有index页面。

thymeleaf模板引擎

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

注意,每次加了新的依赖,一定要maven - reload!

配置页面路径:

spring:
  thymeleaf:
    prefix: classpath:/templates/

index.html放在这里

image

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>资源管理</title>
</head>
<body>
  Hello world!
</body>
</html>

重启项目,访问:http://localhost/

image

成功了。

获取目录中所有的文件

IndexController.java

@Controller
@ConfigurationProperties(prefix = "root")
@Data
public class IndexController {

    private String diskpath;

    @RequestMapping("/")
    public String index(Model m){
        File[] files = FileUtil.ls(diskpath);
        m.addAttribute("files",files);
        return "index";
    }

}

加@Data是为了自动生成set方法,这样才能让@ConfigurationProperties(prefix = “root”)自动去读取yml中的数据。

添加一个依赖,至于为什么要添加,这个在SpringBoot教程里面讲过了。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>2.5.1</version>
    <optional>true</optional>
</dependency>

注意版本号得是2.5.1,不写版本号默认去下载2.5.2了,我的idea默认的maven下载不到这个jar,估计是源头仓库就没有。

这个问题让站长纠结了好半天。

修改后的index.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>资源管理</title>
</head>
<body>
  <ul>
      <li th:each="file:${files}" th:text="${file.getName()}"></li>

  </ul>
</body>
</html>

效果:

image

丑一点没关系,我们先把功能给实现了。

转载自:http://java18.cn/

posted on   剽悍一小兔  阅读(13)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示