• 在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.bootgroupId>
    			<artifactId>spring-boot-starter-webartifactId>
    		dependency>
    
    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-starter-thymeleafartifactId>
    		dependency>
    
    		<dependency>
    			<groupId>org.projectlombokgroupId>
    			<artifactId>lombokartifactId>
    			<scope>providedscope>
    		dependency>
    		
    		<dependency>
    		    <groupId>org.springframework.bootgroupId>
    		    <artifactId>spring-boot-starter-securityartifactId>
    		dependency>
    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-starter-testartifactId>
    			<scope>testscope>
    		dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

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

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Logintitle>
        <link rel="stylesheet" th:href="@{/css/style.css}" />
    head>
    <body>
        <h2>Loginh2>
        <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">Loginbutton>
        form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在新建一个主页,home.html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Hometitle>
    head>
    <body>
        <h2>欢迎来到miaow的主页!h2>
        <p>Logged in successfully!p>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    之后我们在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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

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

    @Controller
    public class LoginController {
    
        @GetMapping("/login")
        public String login() {
            return "login";
        }
    
        @GetMapping("/home")
        public String home() {
            return "home";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    第四步,我们使用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");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

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

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

    在这里插入图片描述
    在这里插入图片描述
    如果账号密码不对是跳不进去主页的。

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

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

    <span th:text="${variable}">Default Textspan>
    
    • 1

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

    <div th:if="${condition}">Visible if condition is truediv>
    
    • 1

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

    <ul>
      <li th:each="item : ${items}" th:text="${item}">Itemli>
    ul>
    
    • 1
    • 2
    • 3

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

    <a th:href="@{/path/to/page}">Linka>
    
    • 1

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

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

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

    <div th:style="'color: red; font-size: 14px'">Styled Textdiv>
    
    • 1

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

    <div th:class="${condition} ? 'class1' : 'class2'">Conditional Classdiv>
    
    • 1

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

    <div th:switch="${variable}">
      <p th:case="'value1'">Case 1p>
      <p th:case="'value2'">Case 2p>
      <p th:default>Default Casep>
    div>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    需要更多请参照官方文档

  • 相关阅读:
    LVGL---基础对象的样式(styles)
    时序预测 | MATLAB实现BO-CNN-LSTM贝叶斯优化卷积神经网络-长短期记忆网络时间序列预测
    从浏览器输入url到页面加载(五)请求数据在网线中的故事
    git基础
    sql注入--通过修改数据完成注入--一文详细讲解
    C51串口通信(蓝牙)
    RabbitMQ一、RabbitMQ的介绍与安装(docker)
    2023年【金属非金属矿山(地下矿山)安全管理人员】考试题库及金属非金属矿山(地下矿山)安全管理人员模拟考试题
    华为新发布的鸿蒙与目前华为手机的鸿蒙系统有什么差异,OpenHarmony、HarmonyOS、HarmonyOS NEXT的区别详解
    leetCode 283 移动零
  • 原文地址:https://blog.csdn.net/qq_45922256/article/details/134516936