首先导入thymeleaf:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
使用:
只要把HTML页面放在classpath:/templates/下, thymeleaf就能自动渲染
例如, 在resources目录下:
resources目录下创建hello.html
templates目录下创建success.html
controller代码如下:
package com.ryan.springdemothymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controller public class Hellocontroller { @ResponseBody @RequestMapping("/Hello") public String hello(){ return "Hello World!"; } @RequestMapping("/success") public String success(){ return "success.html"; } }
在浏览器访问 localhost:8080/hello.html 可访问hello.html文件
在浏览器访问 localhost:8080/success 可访问success.html文件 (不添加.html)