版权声明:原创 https://blog.csdn.net/rambler_designer/article/details/89033010
前言
在做SSM项目时候,静态页面用的html,动态页面用的是jsp
而在SpringBoot中,官方却不推荐jsp,原因也很简单,这要从jsp运行原理说起
在访问服务器某一个动态页面的时候,jsp页面首先会被web容器编译成一个servlet,而servlet就是一个JVM能够识别的java类
因此jsp是重量级的,他会大大的增加服务器的负担,这与springboot提倡的微服务显然相悖,因此springboot推荐thymeleaf
简单说,Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP
示例:
项目结构
POM依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
控制层,这里实现的是"/",也就是访问的根,输入localhost:8080,即可,【可以用这个思路实现首页效果】
package com.rambler.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
private static final String INDEX = "thymeleaf/index";
@RequestMapping("/")
public String welcomePage(Model model){
model.addAttribute("name","rambler_designer");
return INDEX;
}
}
thymeleaf页面(实质就是html,不过加入了一些特定标签)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../css/base.css"/>
<script src="../js/index.js"></script>
</head>
<body>
<h2 th:text="${name}"></h2>
</body>
</html>
application.properties设置
#server port
server.port=80
#config thymeleaf
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
效果