转自:https://segmentfault.com/a/1190000011149325
前言
Spring-boot-starter-web集成了Tomcat以及Spring MVC,会自动配置相关东西,Thymeleaf是用的比较广泛的模板引擎
1.引入依赖
org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web
2.在一个名为application.propertiesde 的文件中配置Thymeleaf
server.port=8080spring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.check-template-location=true spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.thymeleaf.mode=HTML5
3.文件结构
4.Controller
package com.dlp.Controller;import com.dlp.model.Person;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/9/6. */ @Controller public class HelloController { @RequestMapping(value = "/index") public String index(Model model) { Person single = new Person("hyj",21); Listpeople = new ArrayList (); Person p1 = new Person("dlp",21); Person p2 = new Person("tq",21); Person p3 = new Person("mk",21); people.add(p1); people.add(p2); people.add(p3); model.addAttribute("singlePerson",single); model.addAttribute("people",people); return "index"; } }
这里使用@Controller而不用@RESTController是因为这里返回一个页面而不是一个值,如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
5.Model类
package com.dlp.model;/** * Created by Administrator on 2017/9/6. */public class Person { private String name; private Integer age; public Person() { super(); } public Person(String name,Integer gae) { super(); this.name=name; this.age=gae; } public String getName() { return name; } public void setName(String name) { this.name=name; } public Integer getAge() { return age; } public Integer setAge(Integer age) { return age; } }
6.index页面
访问model
列表
xmlns:th="http://www.thymeleaf.org"命名空间,将镜头转化为动态的视图,需要进行动态处理的元素使用“th:”前缀;两个link引入bootstrap框架,通过@{}引入web静态资源(括号里面是资源路径)访问model中的数据通过${}访问,案例
7.运行