前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java小白翻身-基于SpringBoot的文件下载系统 2

Java小白翻身-基于SpringBoot的文件下载系统 2

作者头像
剽悍一小兔
发布2021-07-13 11:38:52
3730
发布2021-07-13 11:38:52
举报
文章被收录于专栏:web编程技术分享

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

创建一个IndexController

代码语言:javascript
复制
@Controller
public class IndexController {

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

}

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

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

thymeleaf模板引擎

添加依赖

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

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

配置页面路径:

代码语言:javascript
复制
spring:
  thymeleaf:
    prefix: classpath:/templates/

index.html放在这里

image

代码语言:javascript
复制
<!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

代码语言:javascript
复制
@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教程里面讲过了。

代码语言:javascript
复制
<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

代码语言:javascript
复制
<!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/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建一个IndexController
  • thymeleaf模板引擎
  • 获取目录中所有的文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档