SpringBoot项目中templates目录的资源访问问题

您所在的位置:网站首页 springboot配置访问html SpringBoot项目中templates目录的资源访问问题

SpringBoot项目中templates目录的资源访问问题

2023-10-18 22:28| 来源: 网络整理| 查看: 265

        在SpringBoot项目中,一般都把静态资源放在 static目录 下,而页面放在 templates目录 下

        SpringBoot默认静态资源映射文件夹是 /static/ 或 /public/ 或 /resources/ 或 /META-INF/resources/,并没有 templates目录,那么为什么我们平时使用起来却没有问题呢

        原因是我们一般都整合了thymeleaf,Springboot和thymeleaf的整合中,对templates目录进行了处理,使我们可以通过Controller返回ModelAndView后,间接访问到templates目录下的资源,但是整合了thymeleaf后,也只能通过这种间接的方式访问,而不能直接访问。

        想要直接访问访问thymeleaf目录下的静态资源,SpringBoot静态资源映射文件夹中添加templates目录。

以下举例:

情况一(假设有以下条件):

文件目录: resources: static: index.html templates: login.html application.yaml application.yaml: 设置视图前缀、后缀 spring: mvc: view: prefix: / suffix: .html Controller中的方法: @RequestMapping("/index") public String test1(){ return "index"; } @RequestMapping("/login") public String test2(){ return "login"; }

 浏览器发起请求:

1、localhost:8080/index.html 访问index.html成功 2、localhost:8080/index 访问index.html成功 3、localhost:8080/login.html 访问login.html失败 4、localhost:8080/login 访问login.html失败

 情况二(假设有以下条件):

文件目录: resources: static: index.html templates: login.html application.yaml application.yaml: 设置视图前缀、后缀 spring: mvc: view: prefix: / suffix: .html Controller中的方法: @RequestMapping("/index") public String test1(){ return "index"; } @RequestMapping("/login") public String test2(){ return "login"; } pom.xml: 整合了thymeleaf org.springframework.boot spring-boot-starter-thymeleaf

 浏览器发起请求:

1、localhost:8080/index.html 访问index.html成功 2、localhost:8080/index 访问index.html成功 3、localhost:8080/login.html 访问login.html失败 4、localhost:8080/login 访问login.html成功

 情况三(假设有以下条件):

文件目录: resources: static: index.html templates: login.html application.yaml application.yaml: 设置视图前缀、后缀 spring: mvc: view: prefix: / suffix: .html resources: 设置templates目录为映射目录 static-locations: classpath:/static/,classpath:/templates/ Controller中的方法: @RequestMapping("/index") public String test1(){ return "index"; } @RequestMapping("/login") public String test2(){ return "login"; } pom.xml: 整合了thymeleaf org.springframework.boot spring-boot-starter-thymeleaf

 浏览器发起请求:

1、localhost:8080/index.html 访问index.html成功 2、localhost:8080/index 访问index.html成功 3、localhost:8080/login.html 访问login.html成功 4、localhost:8080/login 访问login.html失败



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3