当前位置: 首页 > article >正文

在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官网进行开发。

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

		<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文件

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

<!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文件,用于自定义登录页面的样式

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类,用来处理登录页面和主页的请求

@Controller
public class LoginController {

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

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

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

@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:用于将文本内容设置到元素的文本中。

<span th:text="${variable}">Default Text</span>

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

<div th:if="${condition}">Visible if condition is true</div>

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

<ul>
  <li th:each="item : ${items}" th:text="${item}">Item</li>
</ul>

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

<a th:href="@{/path/to/page}">Link</a>

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

<img th:src="@{/path/to/image.jpg}" alt="Image">

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

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

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

<div th:class="${condition} ? 'class1' : 'class2'">Conditional Class</div>

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

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

需要更多请参照官方文档


http://www.kler.cn/news/137018.html

相关文章:

  • 落实“双碳”行动,深兰科技推动分子能源技术在AI硬件产品领域的应用及产业化进程
  • docker 同宿主机不同网络容器通信+跨宿主机容器之间网络互连详解
  • Docker基础部署
  • 高并发下如何保证接口的幂等性?
  • 网络安全中的日志审计:为何至关重要?
  • 排序算法 —— 快速排序(理论+代码)
  • 数据库管理-第117期 拿下19c OCM(202301121)
  • Go语言中获取协程ID
  • Golang抓包:实现网络数据包捕获与分析
  • 后端接口测试,令牌校验住,获取tocken 接口的方式
  • centos更换yum源
  • uni-app(1)pages. json和tabBar
  • 如果文件已经存在与git本地库中,配置gitignore能否将其从git库中删除
  • 【python学习】基础篇-常用函数-sorted() 对可迭代对象进行排序
  • 黄鹤楼
  • 大数据研发工程师课前环境搭建
  • java获取shp文件坐标系
  • 计算机类编程课学生编写的代码应该如何管理
  • 一个完备的手游地形实现方案
  • “三面一体”的业务调度方案在运营商订单运营的实践
  • 一个美观且功能丰富的 .NET 控制台应用程序开源库
  • 报错!Jupyter notebook 500 : Internal Server Error
  • hologres 索引与查询优化
  • MFC项目添加CUDA支持
  • leetcode:914. 卡牌分组(python3解法)
  • 如何快速让苹果TF上架