模板引擎
SpringBoot 推荐使用模板引擎来渲染html,如果你不是历史遗留项目,一定不要使用JSP,常用的模板引擎很多,有freemark,thymeleaf等,其实都大同小异。
其中springboot 强烈推荐的是用thymeleaf:
1) pom文件种添加thymeleaf的支持,并且删除JSP的支持:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--<!–JavaServer Pages Standard Tag Library,JSP标准标签库–>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>jstl</artifactId>-->
<!--</dependency>-->
<!--<!–内置tocat对Jsp支持的依赖,用于编译Jsp–>-->
<!--<dependency>-->
<!--<groupId>org.apache.tomcat.embed</groupId>-->
<!--<artifactId>tomcat-embed-jasper</artifactId>-->
<!--</dependency>-->
2)删除application.properties文件里面视图解析器内容:
~~#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp~~
3)新建Controller内容如下
package cn.enjoy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
@RequestMapping("/testThymeleaf")
public String testThymeleaf(ModelMap map) {
// 设置属性
map.addAttribute("name", "enjoy");
// testThymeleaf:为模板文件的名称
// 对应src/main/resources/templates/testThymeleaf.html
return "testThymeleaf";
}
}
4)Springboot默认的模板配置路径为:src/main/resources/templates:
在resources目录里面新建一个templates目录,在目录里面新建testThymeleaf.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。
上一章:springboot简单入门(5-1):前端界面-Jsp集成
下一章:springboot简单入门(6):Spring Boot 热加载/部署