使用SpringBoot写一个Thymeleaf入门小程序

在Springboot中,推荐使用的view是Thymeleaf,而不是jsp。尽管身为Java程序员,对jsp有着非常深厚的感情,但现在不得不赶紧学习Thymeleaf了。

本次实验使用了Thymeleaf的简单标签,进行入门。
首先导入Thymeleaf的依赖:

<!--导入html依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

application.properties中加入相关配置:

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
#thymeleaf end

一个普通的JavaBean:

package com.example.demo.dao;

public class Person {
	private String name;
	private Integer age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Person() {
		super();
	}
	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
}

编写Controller,将我们需要展示到前端的对象存到Model中,前端便可以动态取用:
这里我们把一个List和一个Person对象加到了Model中

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.dao.Person;


@Controller
public class LoginController {
	
	@RequestMapping(value="/index")	
	public String index(Model model) {
		Person single = new Person("张伟", 27);
		List<Person> list = new ArrayList<Person>();	
		list.add(new Person("曾小贤", 26));
		list.add(new Person("胡一菲", 22));
		list.add(new Person("吕子乔", 24));	
		model.addAttribute("single", single);
		model.addAttribute("peopleList", list);
		return "index";
	}
}

接下来编写前端展示页面,因为html是静态的,不能动态取数据,所以以前我们用的是jsp来配合后端。现在在Springboot中我们用Thymeleaf。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
<!-- 输出peopleList -->
<div th:if="${peopleList != null}">
	<ul th:each="person:${peopleList}">
		<li th:text="${person.name}"></li>
	</ul>
</div>
<!-- 输出Model对象中的single属性 -->
<div th:if="${single != null}">
	<p th:text="单身狗的人是: + ${single.name}">
	<p th:text="年龄为 +  ${single.age}">
</div>
</body>
</html>

Thymeleaf总体来讲,和html差别不大。它的特点是,动态的地方要用 th 标签属性

这里我们先对peopleList进行一个非空的判断,用th:if标签,然后采用类似EL表达式的th:each标签,循环添加到一个无序列表中。
之后,我们用同样的方法,把single对象从Model中取了出来,然后直接显示到前端去。整个过程是一个动态的,因为渲染的内容是和后端程序有关的。

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值