在Spring Boot中使用Thymeleaf开发Web页面

引言: 为啥写这篇文章呢?我明明就没怎么用过这个Thymeleaf进行web开发,用JSP也行,三剑客也行,或者Vue,React,PHP等等,不好吗?

那我为啥写这篇博客呢?这个写了估计也没几个人看,这是我在写之前就做好心理准备了的,毕竟很多东西都需要参照官网案例进行开发,主要写这个是因为,咱们的Spring Boot官方推荐咱们使用Thymeleaf,Thymeleaf也是有好处的,毕竟他是一种基于java的Web应用程序的服务器端模版引擎,它的主要目标是将模板和业务逻辑分离,使开发人员能够更轻松地开发可维护和可扩展的 Web 应用程序。

  • Thymeleaf:Thymeleaf 是一种服务器端模板引擎,主要用于构建基于 Java 的 Web 应用程序。它的特点是模板语法与 HTML 非常接近,易于编写和理解。Thymeleaf与Spring框架紧密集成,提供了与Spring的标准特性集成的功能。
  • Vue:Vue 是一种用于构建现代化、交互式的前端应用程序的 JavaScript 框架。它采用了组件化的开发方式,使得前端开发更加模块化和可维护。Vue 提供了响应式数据绑定、组件化开发、虚拟 DOM 等特性,使得构建复杂的前端应用变得更加简单和高效。
  • PHP:PHP 是一种服务器端脚本语言,主要用于构建动态网页和 Web 应用程序。PHP 具有广泛的应用领域,可以与各种数据库和 Web 服务器进行集成。PHP 提供了丰富的函数库和框架,使得开发 Web 应用程序变得更加便捷。
  • React:React 是一种用于构建用户界面的 JavaScript 库。它采用了组件化的开发方式,使得前端开发更加模块化和可复用。React 使用虚拟 DOM 技术来提高性能,并提供了状态管理、组件生命周期等特性,使得构建大规模、高性能的前端应用变得更加容易。

Thymeleaf主要用于服务器端模板渲染,Vue和React主要用于构建现代化的前端应用程序,而PHP是一种服务器端脚本语言,用于构建动态网页和 Web 应用程序。

就这么说吧,其实不论我们选择哪个进行开发,都有他自己的特色,根据我们的项目需求和技术团队,以及个人爱好进行选择吧。

以下是一些使用 Thymeleaf 的好处:

  • 自然的模板语法:Thymeleaf 的模板语法非常接近于 HTML,使得模板易于编写和理解。这使得前端开发人员可以更轻松地参与到模板的开发中。
  • 强大的表达式功能:Thymeleaf 提供了丰富的表达式功能,可以在模板中使用这些表达式来动态地生成内容。这些表达式可以用于访问模型数据、迭代集合、条件判断、计算等,使模板更加灵活和动态。
  • 与 Spring 框架的集成:Thymeleaf 是与 Spring 框架紧密集成的,可以无缝地与 Spring MVC、Spring Boot 等框架一起使用。它提供了与 Spring 的标准特性集成的功能,如表单绑定、国际化支持、安全性等。
  • 可扩展性:Thymeleaf 提供了丰富的扩展机制,可以通过自定义标签、方言等来扩展模板的功能。这使得开发人员可以根据项目的需求定制和扩展 Thymeleaf 的功能。
  • 良好的生态系统:Thymeleaf 拥有一个活跃的社区和广泛的用户群体,提供了大量的文档、教程和示例代码。这使得学习和使用 Thymeleaf 变得更加容易。

Thymeleaf官网


好了写了这么多,估计看文章还不如看代码来的轻松,这里只提供一个使用哪个Thymeleaf的小案例,具体的语法请参照Thymeleaf官网进行开发。

老样子第一步先引入依赖:

xml 复制代码
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- Spring Security -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

第二步,在resources目录下建立一个templates文件夹。之后建立一个login.html文件

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
    <h2>Login</h2>
    <form th:action="@{/login}" method="post">
        <input type="text" name="username" placeholder="Username" required />
        <br/>
        <input type="password" name="password" placeholder="Password" required />
        <br/>
        <button type="submit">Login</button>
    </form>
</body>
</html>

在新建一个主页,home.html

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h2>欢迎来到miaow的主页!</h2>
    <p>Logged in successfully!</p>
</body>
</html>

之后我们在src/main/resources/static/css目录下创建一个style.css文件,用于自定义登录页面的样式

css 复制代码
body {
    background-color: #f2f2f2;
    font-family: Arial, sans-serif;
    text-align: center;
}

h2 {
    color: #333333;
}

form {
    margin-top: 50px;
}

input[type="text"],
input[type="password"] {
    width: 200px;
    padding: 10px;
    margin-bottom: 10px;
}

button {
    padding: 10px 20px;
    background-color: #333333;
    color: #ffffff;
    border: none;
    cursor: pointer;
}

第三步,我们创建一个LoginController类,用来处理登录页面和主页的请求

java 复制代码
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}

第四步,我们使用Spring security创建一个SecurityConfig类,用来配置Spring Security 包括登录页面和验证逻辑:

java 复制代码
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login", "/css/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("{noop}admin").roles("USER");
    }
}

在上述代码中,我们配置了登录页面为/login,主页为/home。用户名为admin,密码为admin

ok,至此,我们就简单实现了一个登录页面跳转到主页了,可以通过直接访问:http://localhost:8080/login,账号密码均为admin,输入后跳转到主页:


如果账号密码不对是跳不进去主页的。

关于更多的Thymeleaf语法请参照官网,这里给出我们常用的:

th:text:用于将文本内容设置到元素的文本中。

html 复制代码
<span th:text="${variable}">Default Text</span>

th:if:用于条件性地显示或隐藏元素。

html 复制代码
<div th:if="${condition}">Visible if condition is true</div>

th:each:用于迭代集合或数组中的元素,并生成相应的HTML。

html 复制代码
<ul>
  <li th:each="item : ${items}" th:text="${item}">Item</li>
</ul>

th:href:用于设置链接的目标URL。

html 复制代码
<a th:href="@{/path/to/page}">Link</a>

th:src:用于设置图像或脚本的源URL。

html 复制代码
<img th:src="@{/path/to/image.jpg}" alt="Image">

th:style:用于设置元素的样式。

html 复制代码
<div th:style="'color: red; font-size: 14px'">Styled Text</div>

th:class:用于设置元素的CSS类。

html 复制代码
<div th:class="${condition} ? 'class1' : 'class2'">Conditional Class</div>

th:switch、th:case和th:default:用于实现类似于Java的switch-case语句的逻辑。

html 复制代码
<div th:switch="${variable}">
  <p th:case="'value1'">Case 1</p>
  <p th:case="'value2'">Case 2</p>
  <p th:default>Default Case</p>
</div>

需要更多请参照官方文档

相关推荐
杨荧26 分钟前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
2401_8576100336 分钟前
SpringBoot实现:校园资料分享平台开发指南
服务器·spring boot·php
这孩子叫逆1 小时前
Spring Boot项目的创建与使用
java·spring boot·后端
Jay_fearless1 小时前
Redis SpringBoot项目学习
spring boot·redis
coderWangbuer2 小时前
基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
spring boot·后端·sql
Kenny.志2 小时前
2、Spring Boot 3.x 集成 Feign
java·spring boot·后端
sky丶Mamba3 小时前
Spring Boot中获取application.yml中属性的几种方式
java·spring boot·后端
千里码aicood4 小时前
【2025】springboot教学评价管理系统(源码+文档+调试+答疑)
java·spring boot·后端·教学管理系统
程序员-珍4 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
liuxin334455664 小时前
教育技术革新:SpringBoot在线教育系统开发
数据库·spring boot·后端