在第一篇http://www.javashuo.com/article/p-gwzjjije-ed.html中咱们搭建了一个简单的springboot程序 ,并让他运行起来。该篇主要介绍下springboot 和Thymeleaf集成(不具体介绍Thymeleaf语法--关于Thymeleaf语法将单独进行介绍)html
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
spring-boot不少配置都有默认配置,好比默认页面映射路径为
classpath:/templates/*.html
一样静态文件路径为
classpath:/static/java
在application.properties中能够配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置同样web
#thymeleaf start spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html #开发时关闭缓存,否则无法看到实时页面 spring.thymeleaf.cache=false #thymeleaf end
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
这个类,上面的配置实际上就是注入到该类中的属性值.编写一个conntroller提供测试数据(这里牵涉到一点和spring mvc相关的内容,咱们后面再介绍,先忽略),代码以下spring
package com.pxk.controller; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.pxk.entity.User; import com.pxk.service.UserService; @Controller @RequestMapping("/user") public class UserController { private Logger logger = Logger.getLogger(UserController.class); @Autowired private UserService userService; @RequestMapping("/userList") public String userList(Model model) { List<User> users=new ArrayList<User>(); for(int i=0;i<10;i++){ User user=new User(); user.setAge(i+20); user.setName("zhang"+i); } model.addAttribute("users", users); model.addAttribute("count", 10); return "userList"; } }
代码解释:提供一个userList方法返回的model中包含一个user数组和count,user是一个普通的实体类,里面有id,age,name三个属性。 方法是彻底spring MVC的内容(若是不熟的朋友请先熟悉下再看后续文章)apache
放到src/main/resources/templates目录下,这是spring boot和Thymeleaf集成的默认配置路径 数组
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>userList</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <!--/*@thymesVar id="name" type="java.lang.String"*/--> <p th:text="'count:' + ${count} + '!'">3333</p> </body> </html>
访问http://localhost:8080/user/userList,便可看到模板获取到后台数据后渲染到页面。缓存
好了,这篇就先到这里,敬请期待下一篇:springboot 入门教程-的运行原理,关键注解和配置。springboot