Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎
,它可以帮助程序员方便地获取前端数据,渲染出一个界面,比如在浏览器中一般会渲染为HTML格式。并且即使前端传参错误,它也可以把最基本的页面样子显示出来,即动静分离。
1.在使用之前,首先要配置pom.xml。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2.编写controller层
import java.util.List;
import com.example.demo.domain.book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class BookController {
@Autowired
private BookService bookService;
/*根据id返回单本图书具体信息*/
@GetMapping("/books/{id}")
public String getOne(@PathVariable long id, Model model){ //model,视图工具
// 接收查询的信息
book book=bookService.find(id);
// 封装了查询的数据
model.addAttribute("bookContext",book);
//指向templates中的book.html
return "book";
}
}
3.编写thymeleaf页面
我们在templates下新建html页面book.html页面。
使用thymeleaf模板需要修改头部。
&