Thymeleaf简介-HelloWorld基本语法:

简介: Thymeleaf简介-HelloWorld基本语法:

Thymeleaf

MVC

提出问题

//返回提示消息方案三:确实能在登录页面显示提示消息,但是实现的方式让我想骂人response. setContentType("text/html;charset=UTF-8");

Printwriter writer = response. getwriter();

writer.write("<!DOCTYPE html>

writer.write("<html>

writer.write(" <head>

writer.write("<base href='/bookstore/'/>

writer.write("<meta charset='UTF-8'/>

writer.write("<title>登录页面</title>

writer.write("<link type'text/css' rel='stylesheet' href='static

writer.write("</head>

我们对HTML的新的期待:既能够正常显示页面,又能在页面中包含动态数据部分。而动态数据单靠HTML本身是无法做到的,所以此时我们需要引入服务器端动态视图模板技术。

从三层结构到MVC

①MVC概念

M:Model模型

V:View视图

C:Controller控制器

MVC是在表述层开发中运用的一种设计理念。

  1. 主张把封装数据的『模型』、
  2. 显示用户界面的『视图』
  3. 协调调度的『控制器』分开。

好处:

  1. 进一步实现各个组件之间的解耦
  2. 让各个组件可以单独维护
  3. 将视图分离出来以后,我们后端工程师和前端工程师的对接更方便

②MVC和三层架构之间关系

前后端工程师对接方式

服务器端渲染:前端工程师把前端页面一整套做好交给后端工程师

前后端分离:开会商量JSON格式,然后分头开发。在后端程序尚不可用时,前端工程师会使用Mock.js生成假数据使用,在后端程序可用后再连接实际后端程序获取真实数据。

Thymeleaf简介

Thymeleaf的同行

JSP、Freemarker、Velocity等等,它们有一个共同的名字:服务器端模板技术。

Thymeleaf官方文档中的介绍

Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide an elegant and highly-maintainable way of creating templates. To achieve this, it builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype. This improves communication of design and bridges the gap between design and development teams. Thymeleaf has also been designed from the beginning with Web Standards in mind – especially HTML5 – allowing you to create fully validating templates if that is a need for you.

官网地址

Thymeleaf优势

  • SpringBoot官方推荐使用的视图模板技术,和SpringBoot完美整合。
  • 不经过服务器运算仍然可以直接查看原始值,对前端工程师更友好。
1. <!DOCTYPE html>
2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
3. <head>
4. <meta charset="UTF-8">
5. <title>Title</title>
6. </head>
7. <body>
8. 
9. <p th:text="${hello}">Original Value</p>
10. 
11. </body>
12. </html>

物理视图和逻辑视图

物理视图

在Servlet中,将请求转发到一个HTML页面文件时,使用的完整的转发路径就是物理视图。

/pages/user/login_success.html

如果我们把所有的HTML页面都放在某个统一的目录下,那么转发地址就会呈现出明显的规律:

/pages/user/login.html/pages/user/login_success.html/pages/user/regist.html /pages/user/regist_success.html

……

路径的开头都是:/pages/user/

路径的结尾都是:.html

所以,路径开头的部分我们称之为视图前缀,路径结尾的部分我们称之为视图后缀。

逻辑视图

物理视图=视图前缀+逻辑视图+视图后缀

上面的例子中:

视图前缀 视图前缀 视图后缀 物理视图
/pages/user/ login .html /pages/user/login.html
/pages/user/ login_success .html /pages/user/login_success.html

在服务器端引入Thymeleaf环境

  1. 加入jar包
  2. 配置上下文参数

物理视图=视图前缀+逻辑视图+视图后缀

1. <!-- 在上下文参数中配置视图前缀和视图后缀 -->
2. <context-param>
3. <param-name>view-prefix</param-name>
4. <param-value>/WEB-INF/view/</param-value>
5. </context-param>
6. <context-param>
7. <param-name>view-suffix</param-name>
8. <param-value>.html</param-value>
9. </context-param>

说明:param-value中设置的前缀、后缀的值不是必须叫这个名字,可以根据实际情况和需求进行修改。

为什么要放在WEB-INF目录下?

原因:WEB-INF目录不允许浏览器直接访问,所以我们的视图模板文件放在这个目录下,是一种保护。以免外界可以随意访问视图模板文件。

访问WEB-INF目录下的页面,都必须通过Servlet转发过来,简单说就是:不经过Servlet访问不了。

这样就方便我们在Servlet中检查当前用户是否有权限访问。

那放在WEB-INF目录下之后,重定向进不去怎么办?

重定向到Servlet,再通过Servlet转发到WEB-INF下。

创建Servlet基类

这个类大家直接复制粘贴即可,将来使用框架后,这些代码都将被取代。

1. import org.thymeleaf.TemplateEngine;
2. import org.thymeleaf.context.WebContext;
3. import org.thymeleaf.templatemode.TemplateMode;
4. import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
5. 
6. import javax.servlet.ServletContext;
7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11. import java.io.IOException;
12. 
13. public class ViewBaseServlet extends HttpServlet {
14. 
15. private TemplateEngine templateEngine;
16. 
17. @Override
18. public void init() throws ServletException {
19. 
20. // 1.获取ServletContext对象
21. ServletContext servletContext = this.getServletContext();
22. 
23. // 2.创建Thymeleaf解析器对象
24. ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
25. 
26. // 3.给解析器对象设置参数
27. // ①HTML是默认模式,明确设置是为了代码更容易理解
28.         templateResolver.setTemplateMode(TemplateMode.HTML);
29. 
30. // ②设置前缀
31. String viewPrefix = servletContext.getInitParameter("view-prefix");
32. 
33.         templateResolver.setPrefix(viewPrefix);
34. 
35. // ③设置后缀
36. String viewSuffix = servletContext.getInitParameter("view-suffix");
37. 
38.         templateResolver.setSuffix(viewSuffix);
39. 
40. // ④设置缓存过期时间(毫秒)
41.         templateResolver.setCacheTTLMs(60000L);
42. 
43. // ⑤设置是否缓存
44.         templateResolver.setCacheable(true);
45. 
46. // ⑥设置服务器端编码方式
47.         templateResolver.setCharacterEncoding("utf-8");
48. 
49. // 4.创建模板引擎对象
50.         templateEngine = new TemplateEngine();
51. 
52. // 5.给模板引擎对象设置模板解析器
53.         templateEngine.setTemplateResolver(templateResolver);
54. 
55.     }
56. 
57. protected void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
58. // 1.设置响应体内容类型和字符集
59.         resp.setContentType("text/html;charset=UTF-8");
60. 
61. // 2.创建WebContext对象
62. WebContext webContext = new WebContext(req, resp, getServletContext());
63. 
64. // 3.处理模板数据
65.         templateEngine.process(templateName, webContext, resp.getWriter());
66.     }
67. }

HelloWorld

创建index.html

在index.html编写超链接

<a href="/view/TestThymeleafServlet">初步测试Thymeleaf</a>

创建Servlet

1. <servlet>
2. <servlet-name>TestThymeleafServlet</servlet-name>
3. <servlet-class>com.atguigu.thymeleaf.servlet.TestThymeleafServlet</servlet-class>
4. </servlet>
5. <servlet-mapping>
6. <servlet-name>TestThymeleafServlet</servlet-name>
7. <url-pattern>/TestThymeleafServlet</url-pattern>
8. </servlet-mapping>

修改Servlet继承的父类

在doGet()方法中跳转到Thymeleaf页面

1. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2. 
3. // 1.声明当前请求要前往的视图名称
4. String viewName = "target";
5. 
6. // 2.调用ViewBaseServlet父类中的解析视图模板的方法
7. super.processTemplate(viewName, request, response);
8. 
9. }

Thymeleaf页面

1. <!DOCTYPE html>
2. 
3. <!-- 在html标签内加入Thymeleaf名称空间的声明 -->
4. <html lang="en" xmlns:th="http://www.thymeleaf.org">
5. <head>
6. <meta charset="UTF-8">
7. <title>Title</title>
8. </head>
9. <body>
10. 
11. <!-- 在p标签的基础上,使用Thymeleaf的表达式,解析了一个URL地址 -->
12. <p th:text="@{'/aaa/bbb/ccc'}">Thymeleaf将在这里显示一个解析出来的URL地址</p>
13. 
14. </body>
15. </html>


本章笔记是观看尚硅谷的JAVAWEB的视频和在网上找的资料 以及自己的理解总结出来的笔记希望可以帮助大家,感谢大家的耐心观看 如有错误请即使联系我 我会及时修正


目录
相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8083 2
|
12天前
|
域名解析 人工智能 Linux
|
20天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10368 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
6天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1567 5
|
9天前
|
云安全 数据采集 人工智能
|
17天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2715 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2483 0