Thymeleaf模板引擎和Webjars联合使⽤

2018-09-08  本文已影响0人  陶然然_niit

1. 添加Thymeleaf依赖

<!--thymeleaf模板引擎依赖--> 1
<dependency> 2
<groupId>org.springframework.boot</groupId> 3
<artifactId>spring-boot-starter-thymeleaf</artifactId> 4
</dependency>

2. 代码⽬录结构

resources下static⽂件夹存放images、css、js等静态资源
templates存放Thymeleaf模板⻚⾯


resources目录结构含义

3. Controller层代码写法

package com.example.quickstart.controller; 
import com.example.quickstart.entity.Student; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.GetMapping; 
import javax.annotation.Resource; 
@Controller 
public class IndexController { 
//注入了一个Student类的对象,被Spring容器托管 
@Resource 
private Student student; 
//Get请求映射 
@GetMapping("index") 
public String index(ModelMap map) { 
student.setName("Tom"); 
student.setAge(20); 
student.setMale("男"); 
//将模型加入视图 
map.addAttribute("student",student); 
return "index"; 
} 
} 

4. html⻚⾯头部添加thymeleaf名称空间声明

<html xmlns:th="http://www.thymeleaf.org"> 1
<html lang="en"> 2
<head> 3
<meta charset="UTF-8"> 4
<title>主页</title> 5
</head> 6
<body> 7
<p th:text="${stduent.name}"></p> 8
</body> 9
</html>

5. 通过Webjars引⽤静态资源

<dependency> 
<groupId>org.webjars</groupId> 
<artifactId>bootstrap</artifactId> 
<version>3.3.7-1</version> 
</dependency> 
<html xmlns:th="http://www.thymeleaf.org"> 1
<html lang="zh-CN"> 2
<head> 3
<meta charset="UTF-8"/> 4
<title>欢迎页面</title> 5
<link rel="stylesheet"  6
href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" /> 7
<body> 8
<div class="alert alert-success"> 9
<p th:text="${info}"></p> 10
</div> 11
</div> 
上一篇下一篇

猜你喜欢

热点阅读