博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot 整合 Thymeleaf 完整 Web 案例
阅读量:7087 次
发布时间:2019-06-28

本文共 9751 字,大约阅读时间需要 32 分钟。

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢!

Thymeleaf 是一种模板语言。那模板语言或模板引擎是什么?常见的模板语言都包含以下几个概念:数据(Data)、模板(Template)、模板引擎(Template Engine)和结果文档(Result Documents)。

  • 数据
    数据是信息的表现形式和载体,可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的,数据是信息的表达,信息是数据的内涵。数据本身没有意义,数据只有对实体行为产生影响时才成为信息。
  • 模板
    模板,是一个蓝图,即一个与类型无关的类。编译器在使用模板时,会根据模板实参对模板进行实例化,得到一个与类型相关的类。
  • 模板引擎
    模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
  • 结果文档
    一种特定格式的文档,比如用于网站的模板引擎就会生成一个标准的HTML文档。

模板语言用途广泛,常见的用途如下:

  • 页面渲染
  • 文档生成
  • 代码生成
  • 所有 “数据+模板=文本” 的应用场景

这里案例用途自然是 页面渲染,下面在 Spring Boot 中整合 Thymeleaf 实现完整 Web 案例。

一、运行 chapter-2-spring-boot-quick-start

chapter-2-spring-boot-quick-start 工程用的是内存式数据库,不需要配置数据源。下载运行即可。

1. 下载工程

git clone 下载工程 springboot-learning-example ,项目地址见 GitHub:,即:

git clone https://github.com/JeffLi1993/springboot-learning-example.git

2. 工程结构

用 IDEA 打开工程,可以看到子工程 chapter-2-spring-boot-quick-start ,其目录如下:

├── pom.xml└── src    ├── main    │   ├── java    │   │   └── spring    │   │       └── boot    │   │           └── core    │   │               ├── QuickStartApplication.java    │   │               ├── domain    │   │               │   ├── User.java    │   │               │   └── UserRepository.java    │   │               ├── service    │   │               │   ├── UserService.java    │   │               │   └── impl    │   │               │       └── UserServiceImpl.java    │   │               └── web    │   │                   └── UserController.java    │   └── resources    │       ├── application.properties    │       ├── static    │       │   ├── css    │       │   │   └── default.css    │       │   └── images    │       │       └── favicon.ico    │       └── templates    │           ├── userForm.html    │           └── userList.html    └── test        └── java            └── spring                └── boot                    └── core                        ├── QuickStartApplicationTests.java                        └── domain                            └── UserRepositoryTests.java

对应目录:

  • org.spring.springboot.controller - Controller 层
  • org.spring.springboot.dao - 数据操作层 DAO
  • org.spring.springboot.domain - 实体类
  • org.spring.springboot.service - 业务逻辑层
  • Application - 应用启动类
  • application.properties - 应用配置文件

模板是会用到下面两个目录

  • static 目录是存放 CSS、JS 等资源文件
  • templates 目录是存放视图

3. 编译运行工程

在该工程根目录,运行 maven 指令进行编译:

cd chapter-2-spring-boot-quick-startmvn clean install

编译工程成功后,右键运行名为 QuickStartApplication.java 应用启动类的 main 函数,然后浏览器访问 localhost:8080/users 即可:

用户列表页面:
用户编辑页面:

二、详解 chapter-2-spring-boot-quick-start

工程代码:

1. pom.xml Thymeleaf 依赖

使用模板引擎,就在 pom.xml 加入 Thymeleaf 组件依赖:

org.springframework.boot
spring-boot-starter-thymeleaf

Thymeleaf 是什么?

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推荐使用。

整体个 pom.xml 配置如下:

4.0.0
spring.boot.core
chapter-2-spring-boot-quick-start
0.0.1-SNAPSHOT
jar
chapter-2-spring-boot-quick-start
第二章快速入门案例
org.springframework.boot
spring-boot-starter-parent
1.5.7.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-jpa
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-maven-plugin

2. Thymeleaf 依赖配置

在 Spring Boot 项目中加入 Thymeleaf 依赖,即可启动其默认配置。如果想要自定义配置,可以在 application.properties 配置如下:

spring.thymeleaf.cache=true # Enable template caching.spring.thymeleaf.check-template=true # Check that the template exists before rendering it.spring.thymeleaf.check-template-location=true # Check that the templates location exists.spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.spring.thymeleaf.encoding=UTF-8 # Template files encoding.spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

3. Thymeleaf 使用

Controller 如何将 View 指向 Thymeleaf

用户控制层代码如下:

@Controller@RequestMapping(value = "/users")     // 通过这里配置使下面的映射都在 /userspublic class UserController {    @Autowired    UserService userService;          // 用户服务层    /**     *  获取用户列表     *    处理 "/users" 的 GET 请求,用来获取用户列表     *    通过 @RequestParam 传递参数,进一步实现条件查询或者分页查询     */    @RequestMapping(method = RequestMethod.GET)    public String getUserList(ModelMap map) {        map.addAttribute("userList", userService.findAll());        return "userList";    }    /**     * 显示创建用户表单     *     */    @RequestMapping(value = "/create", method = RequestMethod.GET)    public String createUserForm(ModelMap map) {        map.addAttribute("user", new User());        map.addAttribute("action", "create");        return "userForm";    }    /**     *  创建用户     *    处理 "/users" 的 POST 请求,用来获取用户列表     *    通过 @ModelAttribute 绑定参数,也通过 @RequestParam 从页面中传递参数     */    @RequestMapping(value = "/create", method = RequestMethod.POST)    public String postUser(@ModelAttribute User user) {        userService.insertByUser(user);        return "redirect:/users/";    }    /**     * 显示需要更新用户表单     *    处理 "/users/{id}" 的 GET 请求,通过 URL 中的 id 值获取 User 信息     *    URL 中的 id ,通过 @PathVariable 绑定参数     */    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)    public String getUser(@PathVariable Long id, ModelMap map) {        map.addAttribute("user", userService.findById(id));        map.addAttribute("action", "update");        return "userForm";    }    /**     * 处理 "/users/{id}" 的 PUT 请求,用来更新 User 信息     *     */    @RequestMapping(value = "/update", method = RequestMethod.POST)    public String putUser(@ModelAttribute User user) {        userService.update(user);        return "redirect:/users/";    }    /**     * 处理 "/users/{id}" 的 GET 请求,用来删除 User 信息     */    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)    public String deleteUser(@PathVariable Long id) {        userService.delete(id);        return "redirect:/users/";    }}

ModelMap 对象来进行数据绑定到视图。return 字符串,该字符串对应的目录在 resources/templates 下的模板名字。

@ModelAttribute 注解是用来获取页面 Form 表单提交的数据,并绑定到 User 数据对象。

Form 表单页面

核心代码:

  

这里定义了一个 Form 表单用于新增或者更新用户。

列表页面

代码如下:

                    用户列表                
用户编号 名称 年龄 出生时间 管理
删除

这里循环了用户列表。

Tymeleaf 的语法糖

我这边也就不详细展开了,大家看看人家写的

或者看看官方文档

三、本文小结

该文,利用 Thymeleaf 做了个 Web 的 CRUD 案例。大家多指教~

如以上文章或链接对你有帮助的话,别忘了在文章结尾处评论哈~ 你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章。

你可能感兴趣的文章
第3大的数 Third Maximum Number
查看>>
微信支付的Code如何获取?
查看>>
Oracle 数据库入门之----------------------多表查询
查看>>
Oracle数据库DBA专题技术精粹
查看>>
[转]solr入门
查看>>
Haproxy部署网站LB集群
查看>>
Asterisk与LYNC联机
查看>>
firewall ports for ESXi 6.x
查看>>
【4】万魂杀服务器开发方面之配置生成工具
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
相对路径和绝对路径 目录的创建 cd mkdir rm 等命令
查看>>
MongoDB基本管理命令
查看>>
文件/文件夹操作
查看>>
dubbo-spring-boot-starter
查看>>
iterator
查看>>
[瞎折腾]使用freemarker编写MyBatis的Mapper.xml自动生成工具
查看>>
linux下环境变量汇总
查看>>
C/C++实现环形缓冲
查看>>
我的友情链接
查看>>