1. 项目结构
2. 在pom.xml文件中添加thymeleaf依赖
<!-- 添加thymeleaf依赖 -->3. 在application.properties中添加thymeleaf配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#spring.thymeleaf.prefix=classpath:/templates/4. 在src/main/resources/templates/添加hello.html,内容如下:
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html
#设置thymeleaf的缓存是否关闭,开发阶段建议关闭
spring.thymeleaf.cache=false
<!DOCTYPE html>5. 编写TemplatesController
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
Hello,<span th:text="${nameKey}"></span>
</body>
</html>
package com.lanhuigu;6. 编写启动类App
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 注意: 这个地方使用的是@Controller,而不是@RestController,用的是spring MVC逻辑,
* 在spring MVC中,需要在spring mvc配置的视图解析器中指定视图文件位置,spring boot使用
* thymeleaf等于将视图地址默认在src/main/resources/templates下了
*/
@Controller
@RequestMapping("/templates")
public class TemplatesController {
@RequestMapping("/helloHtml")
public String helloHtml(Map<String,Object> map) {
map.put("nameKey", "Thymeleaf");
return "hello";
}
}
package com.lanhuigu;7. 启动服务访问,默认端口8080
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
* 启动类
*/
@SpringBootApplication
public class App {
public static void main( String[] args ) {
/*System.out.println( "Hello World!" );*/
SpringApplication.run(App.class, args);
}
}