在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>

需要更多请参照官方文档

相关推荐
用户83071968408212 小时前
Spring Boot 集成 RabbitMQ :8 个最佳实践,杜绝消息丢失与队列阻塞
spring boot·后端·rabbitmq
Java水解13 小时前
Spring Boot 视图层与模板引擎
spring boot·后端
Java水解13 小时前
一文搞懂 Spring Boot 默认数据库连接池 HikariCP
spring boot·后端
洋洋技术笔记17 小时前
Spring Boot Web MVC配置详解
spring boot·后端
初次攀爬者1 天前
Kafka 基础介绍
spring boot·kafka·消息队列
用户8307196840821 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Java水解2 天前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
初次攀爬者2 天前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺2 天前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart2 天前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot