SpringBoot整合Thymeleaf
一个整合Thymeleaf与Mybatis的CRUD例子
一、添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、yml文件
spring:
thymeleaf:
#模板编码
mode: LEGACYHTML5
#是否缓存 别闹不缓存
cache: false
# 在构建URL时预先查看名称的前缀
prefix: classpath:/templates/
# 构建URL时附加查看名称的后缀.
suffix: .html
三、sql语句
CREATE TABLE `user` (
`id` INT(9) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(10) DEFAULT NULL,
`age` INT(3) DEFAULT NULL,
`birth_day` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO test.user (NAME,age,birth_day) VALUES ("xiaoming",18,NOW());
INSERT INTO test.user (NAME,age,birth_day) VALUES ("xiaohua",19,NOW());
四、静态html文件
1、index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:replace="~{header::header}"></div>
<h3 th:text="${userModel.title}"></h3>
<div>
<a th:href="@{/user/form}">创建用户</a>
</div>
<table border="1">
<thead>
<tr>
<td>ID</td>
<td>age</td>
<td>Name</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">没有用户信息!</td>
</tr>
<tr th:each="user:${userModel.userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.age}"></td>
<td >
<a th:href="@{'/user/info/'+${user.id}}" th:text="${user.name}"></a>
</td>
<td >
<a th:href="@{'/user/delete/'+${user.id}}">删除</a>
<a th:href="@{'/user/modify/'+${user.id}}">修改</a>
</td>
</tr>
</tbody>
</table>
<div th:replace="~{footer::footer}"></div>
</body>
</html>
2、add.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:replace="~{header::header}"></div>
<h3 th:text="${userModel.title}"></h3>
<form action="/user/save" th:action="@{/user/save}" method="POST" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
年龄:<br>
<select id="age" name="age" th:value="*{age}">
<!--<option value="99" selected="true">请选择控制时间</option>-->
<option th:if="${'1'=='1' && '0'=='0'}" th:each="i:${#numbers.sequence(1,150)}" th:selected="${i+'' eq '18' }" th:value="${i}" th:text="${i}" ></option>
</select>
生日:<br>
<input type="text" name="birthDay" th:value="*{birthDay}">
<input type="submit" value="提交" >
</form>
<div th:replace="~{footer::footer}"></div> <script> </script>
</body>
</html>
3、info.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:replace="~{header::header}"></div>
<h3 th:text="${userModel.title}"></h3>
<div>
<p><strong>ID:</strong><span th:text="${userModel.user.id}"></span></p>
<p><strong>Name:</strong><span th:text="${userModel.user.name}"></span></p>
<p><strong>age:</strong><span th:text="${userModel.user.age}"></span></p>
<p><strong>birthDay:</strong><span th:text="${userModel.user.birthDay}"></span></p>
</div>
<div th:replace="~{footer::footer}"></div>
</body>
</html>
4、modify.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:replace="~{header::header}"></div>
<h3 th:text="${userModel.title}"></h3>
<form action="/user/update" th:action="@{/user/update}" method="POST" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
年龄:<br>
<select id="age" name="age" >
<!--<option value="99" selected="true">请选择控制时间</option>-->
<option th:if="${'1'=='1' && '0'=='0'}" th:each="i:${#numbers.sequence(1,150)}" th:selected="${i eq user.age }" th:value="${i}" th:text="${i}" ></option>
</select>
生日:<br>
<input type="text" name="birthDay" th:value="*{birthDay}">
<input type="submit" value="提交" >
</form>
<input type="hidden" name="iasdasdd" th:value="${userModel.user.age}">
<div th:replace="~{footer::footer}"></div>
</body>
</html>
5、footer.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:fragment="footer">
<a href="http://www.baidu.com">百度一下</a>
</div>
</body>
</html>
6、header.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultrag.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
<div th:fragment="header">
<h1>Thymeleaf in action</h1>
<a href="/user/index" >首页</a>
</div>
</body>
</html>
五、java文件
1、UserController
package com.ydj.yboot.web.controller; import com.ydj.yboot.web.domain.User;
import com.ydj.yboot.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView; /**
* @author yuduojia
* @date 2019/5/24 13:17
*/
@RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserService userService; @GetMapping("/index")
public ModelAndView list(Model model) {
model.addAttribute("userList",userService.getUserList());
model.addAttribute("title", "用户管理");
return new ModelAndView("user/index","userModel",model);
} @GetMapping("/form")
public ModelAndView createForm(Model model) {
model.addAttribute("user",new User());
model.addAttribute("title", "创建用户");
return new ModelAndView("user/add","userModel",model);
} @PostMapping("/save")
public ModelAndView saveOrUpdateUser( User user) {
int i = userService.saveUser(user);
return new ModelAndView("redirect:/user/index");//重定向到list页面
} @GetMapping("/delete/{id}")
public ModelAndView deleteUser(@PathVariable("id") Long id) {
userService.deleteUser(id);
return new ModelAndView("redirect:/user/index");//重定向到list页面
} @GetMapping("/info/{id}")
public ModelAndView view(@PathVariable("id") Long id,Model model) {
User user = userService.getUserById(id);
model.addAttribute("user",user);
model.addAttribute("title", "查看用户");
return new ModelAndView("user/info","userModel",model);
} @GetMapping("/modify/{id}")
public ModelAndView modifyUser(@PathVariable("id") Long id, Model model) {
model.addAttribute("user",userService.getUserById(id));
model.addAttribute("title", "修改用户");
return new ModelAndView("user/modify","userModel",model);
} @PostMapping("/update")
public ModelAndView updateUser(User user) {
int l = userService.updateUser(user);
return new ModelAndView("redirect:/user/index");//重定向到list页面
}
}
2、UserService
package com.ydj.yboot.web.service; import com.ydj.yboot.web.domain.User; import java.util.List; /**
* @author yuduojia
* @date 2019/5/24 13:20
*/
public interface UserService {
List<User> getUserList(); int saveUser(User user); void deleteUser(Long id); User getUserById(Long id); int updateUser(User user);
}
3、UserServiceImpl
package com.ydj.yboot.web.service.impl; import com.ydj.yboot.web.dao.UserDao;
import com.ydj.yboot.web.domain.User;
import com.ydj.yboot.web.service.UserService;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.util.List; /**
* @author yuduojia
* @date 2019/5/24 13:21
*/
@Service
public class UserServiceImpl implements UserService { @Resource
private UserDao userDao; @Override
public List<User> getUserList() {
return userDao.getUserList();
} @Override
public int saveUser(User user) {
return userDao.saveUser(user);
} @Override
public void deleteUser(Long id) {
userDao.deleteUser(id);
} @Override
public User getUserById(Long id) {
return userDao.getUserById(id);
} @Override
public int updateUser(User user) {
return userDao.updateUser(user);
} }
4、UserDao
package com.ydj.yboot.web.dao; import com.ydj.yboot.web.domain.User;
import org.apache.ibatis.annotations.Mapper; import java.util.List; /**
* @author yuduojia
* @date 2019/5/24 13:21
*/
@Mapper
public interface UserDao { List<User> getUserList(); int saveUser(User user); void deleteUser(Long id); User getUserById(Long id); int updateUser(User user);
}
5、user
package com.ydj.yboot.web.domain; import java.io.Serializable;
import java.util.Date; /**
* @author yuduojia
* @date 2019/5/24 13:14
*/
public class User implements Serializable { private int id;
private String name;
private int age;
private String birthDay;
// private Dept dept;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getBirthDay() {
return birthDay;
} public void setBirthDay(String birthDay) {
this.birthDay = birthDay;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", birthDay=" + birthDay +
'}';
}
}
六、静态mapper.xml文件 UserMapper.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ydj.yboot.web.dao.UserDao"> <select id="getUserList" resultMap="getUserListResultMap">
select * from user
<where>
<if test="id != null and id != ''"> and id = #{id} </if>
<if test="name != null and name != ''"> and name = #{name} </if>
<if test="age != null and age != ''"> and age = #{age} </if>
<if test="birthDay != null and birthDay != ''"> and birth_day = #{birthDay} </if>
</where>
</select> <resultMap id="getUserListResultMap" type="com.ydj.yboot.web.domain.User">
<id column="id" property="id" jdbcType="INTEGER"></id>
<result column="name" property="name" jdbcType="VARCHAR"></result>
<result column="age" property="age" jdbcType="INTEGER"></result>
<result column="birthDay" property="birth_day" jdbcType="TIMESTAMP"></result>
<!--<association property="Dept" javaType="com.ydj.yboot.web.domain.Dept">
<result column="dept_name" property="deptName"></result>
</association>-->
</resultMap> <insert id="saveUser" parameterType="com.ydj.yboot.web.domain.User"
useGeneratedKeys="true" keyProperty="id">
insert into user
(
`name`,
`age`,
`birth_day`
)
values
(
#{name},
#{age},
#{birthDay}
)
</insert> <delete id="deleteUser" parameterType="long" >
delete from user where id = #{value}
</delete> <select id="getUserById" resultType="com.ydj.yboot.web.domain.User">
select * from user where id = #{value}
</select> <update id="updateUser" parameterType="com.ydj.yboot.web.domain.User">
update user
<set>
<if test="name != null">`name` = #{name}, </if>
<if test="age != null">`age` = #{age}, </if>
<if test="birthDay != null">`birth_day` = #{birthDay} </if>
</set>
where id = #{id}
</update> </mapper>
SpringBoot整合Thymeleaf的更多相关文章
- 【Springboot】Springboot整合Thymeleaf模板引擎
Thymeleaf Thymeleaf是跟Velocity.FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点: 1. Thymeleaf在有网络和无 ...
- Springboot整合thymeleaf模板
Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用. Thymeleaf的主要目标在于提供一种可被浏览器正确显示的.格式良好的模板创建方式,因此也可以用作静态建 ...
- 三、SpringBoot整合Thymeleaf视图
目录 3.1 Thymeleaf视图介绍 3.2 创建SpringBoot项目 3.2 配置Thymeleaf 3.3 编写Demo 3.4 小结 3.1 Thymeleaf视图介绍 先看下官网的介绍 ...
- SpringBoot 整合 Thymeleaf & 如何使用后台模板快速搭建项目
如果你和我一样,是一名 Java 道路上的编程男孩,其实我不太建议你花时间学 Thymeleaf,当然他的思想还是值得借鉴的.但是他的本质在我看来就是 Jsp 技术的翻版(Jsp 现在用的真的很少很少 ...
- SpringBoot 整合thymeleaf
1.Thymeleaf介绍(官网推荐:https://www.thymeleaf.org/doc/articles/thymeleaf3migration.html) Thymeleaf是跟Veloc ...
- springboot整合thymeleaf+tiles示例
网上关于此框架的配置实在不多,因此想记录下来以防忘记 因为公司框架基于上述(公司采用gradle构建项目,楼主采用的是maven),所以楼主能少走些弯路: 1.创建springboot-maven项目 ...
- SpringBoot:2.SpringBoot整合Thymeleaf模板引擎渲染web视图
在Web开发过程中,Spring Boot可以通过@RestController来返回json数据,那如何渲染Web页面?Spring Boot提供了多种默认渲染html的模板引擎,主要有以下几种: ...
- springboot整合Thymeleaf模板引擎
引入依赖 需要引入Spring Boot的Thymeleaf启动器依赖. <dependency> <groupId>org.springframework.boot</ ...
- SpringBoot学习9:springboot整合thymeleaf
1.创建maven项目,添加项目所需依赖 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springframewo ...
随机推荐
- [Xcode 实际操作]九、实用进阶-(13)调用相机并获取拍摄后的图片
目录:[Swift]Xcode实际操作 本文将演示如何调用相机并获取拍摄后的图片. 在项目导航区,打开视图控制器的代码文件[ViewController.swift] import UIKit //首 ...
- Metabolic and gut microbial characterization of obesity-prone mice under high-fat diet (文献分享一组-赵容丽)
题目:高脂饮食下易肥胖小鼠的代谢和肠道微生物特性研究 Metabolic and gut microbial characterization of obesity-prone mice under ...
- Django框架的安装,项目创建
目录 Django框架的安装,项目创建 方法安装 Django版本选择 1.11.21(最新LTS版) django管理目录 命令行创建项目 django项目 命令行启动 (必须在项目文件下执行) p ...
- Web前端篇:CSS常用格式化排版、盒模型、浮动、定位、背景边框属性
目录 Web前端篇:CSS常用格式化排版.盒模型.浮动.定位.背景边框属性 1.常用格式化排版 2.CSS盒模型 3.浮动 4.定位 5.背景属性和边框属性 6.网页中规范和错误问题 7.显示方式 W ...
- java数据结构----队列,优先级队列
1.队列:和栈中的情况不同,队列中的数据项不总是从数组下标0开始,移除一个数据项后,队头指针会指向下标较高的数据项,其特点:先入先出 2.图解 3.队列的实现代码: 3.1.Queue.java pa ...
- iOS 更改状态栏、导航栏颜色的几种方法
ios上状态栏 就是指的最上面的20像素高的部分状态栏分前后两部分,要分清这两个概念,后面会用到: 前景部分:就是指的显示电池.时间等部分:背景部分:就是显示黑色或者图片的背景部分: (一)设置sta ...
- String的内存和intern()方法
一.关于常量池 字符串在Java中用的非常得多,Jvm为了减少内存开销和提高性能,使用字符串常量池来进行优化. 在jdk1.7之前(不包括1.7),Java的常量池是在方法区的地方,方法区是一个运行时 ...
- dubbo-spring
一.需求 某个电商系统,订单服务需要调用用户服务获取某个用户的所有地址:创建两个服务模块进行测试 测试预期结果:订单服务web模块在A服务器,用户服务模块在B服务器,A可以远程调用B的功能. 二.工程 ...
- idea中deployment点击加号没有出现artifact
转载 在主页面打开ProjectStructure,点击图示的按钮或是按ctrl+shift+alt+s快捷键 打开ProjectStructure后,按照图示依次点击Facets->+号,在弹 ...
- Java 多个if 和多个else if 的区别
int a=1; if(a==1){System.out.println("1");} if(a==2){System.out.println("2");} i ...