使用thymeleaf解决访问不到templates下的html文件

pom文件

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

resources下的 application.properties文件

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
#上下文--
#不仅仅是一个路劲的前缀,而且是项目的名字groupId
server.servlet.context-path=/

resources下的templates目录下的hello.html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>

<!-- 你的HTML代码 -->
你好,爱上我了
</script>
</body>
</html>
controller中的类,当访问hello路径时会跳转到login的html页面
http://www.localhost:8080/hello
@Controller
public class ConTest {
    @RequestMapping("/hello")
    public String hello(Model model){   
        return "login";
    }
}

 

但是要注意一下这种情况

controller中的只能使用@Controller的注解,不能使用@RestController。

关于@RestController,@Controller,@ResponseBody以及thymeleaf页面的搭配使用,最近我再另外一篇文章进行了使用场景进行了分析。附上链接

https://blog.csdn.net/qq_36838406/article/details/100867004

 

  • 15
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
不可以直接访问`resources/templates`目录下的HTML页面,因为这些页面是动态生成的,需要通过Thymeleaf模板引擎进行渲染。但是,可以通过控制器将这些页面映射到一个URL路径上,然后通过访问这个URL路径来访问这些页面。具体步骤如下: 1. 在`application.properties`中添加以下配置,以指定模板文件的查找目录: ``` spring.thymeleaf.prefix=classpath:/templates/ ``` 这样,Thymeleaf模板引擎将会在`/templates`目录下查找模板文件。 2. 在`resources/templates`目录下创建HTML模板文件,并使用Thymeleaf的语法进行渲染。 3. 创建一个控制器,将该控制器映射到一个URL路径上。例如: ``` @Controller public class MyController { @GetMapping("/my-page") public String myPage(Model model) { // 将数据添加到模型中 model.addAttribute("message", "Hello, world!"); // 返回模板文件名,不需要指定文件扩展名 return "my-page"; } } ``` 这个控制器将会将`/my-page`路径映射到`resources/templates/my-page.html`模板文件。在控制器中使用`Model`对象将需要渲染的数据添加到模型中。控制器中返回的字符串是模板文件文件名,不需要指定文件扩展名。 4. 在HTML模板文件使用Thymeleaf语法渲染数据。例如: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Page</title> </head> <body> <h1 th:text="${message}"></h1> </body> </html> ``` 这里的`${message}`将会被Thymeleaf渲染为控制器中添加到模型中的数据。 5. 访问`/my-page`路径,将会渲染`resources/templates/my-page.html`模板文件,并且显示控制器中添加到模型中的数据。 需要注意的是,`resources/templates`目录下的HTML模板文件并不是静态资源,而是需要经过Thymeleaf模板引擎进行渲染的动态资源。因此,不能直接访问这些文件,必须通过控制器进行访问

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值