最近写一些小功能时,想写些页面验证一下效果,后台用的是SpringBoot,当时想用jsp写页面来着,但是springboot不推荐使用jsp,因为jsp在springboot中有诸多限制。
springboot中推荐使用thymeleaf模板,使用html作为页面展示,所以这篇博客记录一下如何初步使用thymeleaf开发html。
1、在pom.xml文件中添加thymeleaf依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2.在application.xml中添加访问请求配置(也可以是application.yml文件,个人习惯)
#thymeleaf
#默认到resource/templates目录下寻找
spring.thymeleaf.suffix=.html
spring.thymeleaf.check-template-location=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
springboot中默认resources中static文件夹存放静态资源,如js文件、css文件、图片等等。templates文件夹中存放html页面。
3.在templates文件夹中创建html文件
index.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>thymeleaf</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Welcome thymeleaf.</h1>
<a href="/redirect">redirect</a>
<a href="/model">model</a>
</body>
</html>
hello.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>model</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>welcome : [[${name}]].</p>
<h1>hi , [[${boss}]] !</h1>
</body>
</html>
redirect.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>redirectPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>congratulation redirect success !</h1>
</body>
</html>
4.编写Controller
注意:不要使用@RestController注解,@RestController注解是@ResponseBody和@Controller的集合体,使用@RestController注解会默认返回数据,而不会请求到页面。
package com.boss.info.thymeleaf;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by qxr4383 on 2019/3/15.
*/
@Controller
public class pageController {
/**
* 首页
* @return
*/
@RequestMapping("/")
public String page(){
return "system/index";
}
/**
* 跳转
* @return
*/
@RequestMapping("/redirect")
public String page2(){
return "redirect/redirect";
}
/**
*视图
* @param model
* @return
*/
@RequestMapping("/model")
 public String page3(Model model){
model.addAttribute("name","seawater");
model.addAttribute("boss","you will be a boss!");
return "hello";
}
}
5.在浏览器中输入请求地址
localhost:8080
6.静态资源的访问
html页面中使用到静态资源时(如图片),直接使用。js为static下的文件夹。