Spring Boot中,
Groovy
Thymeleaf
Mustache
Spring boot不建议使用jsp开发web。
本文使用Thymeleaf作为模板引擎来开发web项目。
一、在application.properties中设置Thymeleaf相关属性
# Check that the template exists before rendering it.
spring.thymeleaf.check-template=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value written to HTTP responses.
spring.thymeleaf.content-type=text/html
# Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable=true
# Template files encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.exclude-view-names=index
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Disable template caching.
spring.thymeleaf.cache=false
二、在pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
三、在resources目录下创建templates文件夹,并添加模板html
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
姓名:<span th:text="${user.username}"></span></br>
邮箱:<span th:text="${user.email}"></span></br>
昵称:<span th:text="${user.nickname}"></span>
</body>
</html>
四、增加Controller
@Controller
public class TemplatesController {
@Autowired
private UserService userService;
@RequestMapping("/index")
String test(ModelMap map) {
map.addAttribute("key", "thymeleaf");
return "index";
}
@RequestMapping("/test")
public String testThymeleaf(ModelMap map) {
map.addAttribute("user", userService.selectByPrimaryKey(1));
return "test";
}
}
五、运行结果
到这里,Spring Boot + Mybatis +Spring MVC环境就搭建完成了
完整环境下载地址:
https://github.com/CatherineHu/Spring-Boot-Mybatis-MVC