目前Java Web开发推荐使用模板引擎,不建议使用JSP页面
JSP缺点:本质上就是Servlet,需要后台编译,耗时,效率低
模板引擎:不需要编译,速度快
常见的模板引擎:Freemarker、Velocity、Thymeleaf等
SpringBoot推荐使用Thymeleaf(C母赖夫),且默认不支持JSP,因为JSP必须要打包war包才行
现阶段项目中更多使用MVVM框架,前后段分离如:Vue.js、Angular、React。
添加thymeleaf模板引擎需要修改两处文件(其实添加一个pom依赖就ok)。
1.pom文件, <!-- 引入 thymeleaf 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2..application.properties文件,新增下面配置。
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
3.java代码 如下方式,templates目录下的HTML页面默认不能被直接访问,需要通过controller来访问,由thymeleaf来渲染
@ControllerAdvice
@RequestMapping("index")
public class SpringBootController {
@RequestMapping("/thymeleaf")
public String thymeleaf(Model model) {
model.addAttribute("name", "qushen");
System.out.println("从Controller跳转thymeleaf");
return "user/thymeleaf";
}
}
HTML写法如下:具体Thymeleaf写法可以参考官网:https://www.thymeleaf.org/documentation.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>hello Spring boot!</div>
<p th:text="${name}">Welcome to our grocery store!</p>
</body>
</html>s
显示效果如下: