使用SpringBoot + Thymeleaf 完成简单的用户登录

news2025/7/15 6:59:46

😀前言
本篇博文是关于Thymeleaf 的综合案例, 使用SpringBoot + Thymeleaf 完成简单的用户登录-列表功能,希望你能够喜欢😊

🏠个人主页:晨犀主页
🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉
💕欢迎大家:这里是CSDN,我总结知识的地方,欢迎来到我的博客,感谢大家的观看🥰
如果文章有什么需要改进的地方还请大佬不吝赐教 先在此感谢啦😊

文章目录

  • Thymeleaf
    • 官方文档
    • Thymeleaf 综合案例
      • 需求说明
        • 分析图
      • 代码实现
      • 完成测试
    • 😄总结

Thymeleaf

官方文档

在线文档: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
离线文档: usingthymeleaf.pdf

Thymeleaf 综合案例

如果对Thymeleaf感兴趣可以看看小编的Thymeleaf快速入门及其注意事项,希望你能够喜欢😊。

需求说明

说明: 使用SpringBoot + Thymeleaf 完成简单的用户登录-列表功能

image-20230813202058053

image-20230813202114074

分析图

image-20230813202153721

代码实现

  1. 创建项目。

  2. 要使项目支持Thymeleaf, 需要在pom.xml 加入thymeleaf-starter,配置。

image-20230813202405193

  1. 引入starter-Thymeleaf , 项目会自动完成配置, 程序员按照规则开发即可

image-20230813202516536

image-20230813202745817

  1. 创建Login.html和manage.html 和静态图片到指定目录,从准备好的拷贝即可, 注意如果将html 文件放到templates/ 目录下, 该目录不能直接访问

image-20230813203001902

创建Login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<hr/>
<div style="text-align: center">
    <h1>用户登陆</h1>
    <form action="#"  method="post">
        <label style="color: red" th:text="${msg}"></label><br/>
        用户名:<input type="text" style="width:150px" name="name"/><br/><br/>
        密 码:<input type="password" style="width:150px" name="password"/><br/><br/>
        <input type="submit" value="登录"/>
        <input type="reset" value="重新填写"/>
    </form>
</div>
<hr/>
<img src="images/logo.png"/>
</body>
</html>

创建manage.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理后台</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<a href='#'>返回管理界面</a>  <a href='#'>安全退出</a>   欢迎您:xxx
<hr/>
<div style="text-align: center">
    <h1>管理雇员~</h1>
    <table border="1px" cellspacing="0" bordercolor="green" style="width:800px;margin: auto">
        <tr bgcolor="pink">
            <td>id</td>
            <td>name</td>
            <td>pwd</td>
            <td>email</td>
            <td>age</td>
        </tr>
        <tr bgcolor="#ffc0cb" >
            <td>a</td>
            <td>b</td>
            <td>c</td>
            <td>d</td>
            <td>e</td>
        </tr>
    </table>
    <br/>
</div>
<hr/>
<img src="images/logo.png"/>
</body>
</html>
  1. 创建com/nlc/usersys/bean/Admin.java
@Data
public class Admin {
    private String name;
    private String password;
}
  1. 创建com/nlc/usersys/bean/User.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
    private String password;
    private Integer age;
    private String email;
}
  1. 创建com/nlc/usersys/controller/IndexController.java 默认进入登录页面
@Controller
public class IndexController {

    //编写方法,转发到登录页面
    @GetMapping(value = {"/", "/login"})
    public String login() {
        /**
         * 解读
         * 1. 因为我们引入了starter-thymeleaf
         * 2. 这里就会直接使用视图解析到 thymeleaf下的模板文件adminLogin.html
         */
        return "adminLogin";
    }
}
  1. 创建com/nlc/usersys/controller/AdminController.java 处理登录请求完成测试
@Controller
public class AdminController {

    //响应用户的登录请求
    @PostMapping("/login")
    public String login(Admin admin, HttpSession session, Model model) {

        //验证用户是否合法
        if (StringUtils.hasText(admin.getName()) && "666".equals(admin.getPassword())) {

            //将登录用户保存到session
            session.setAttribute("loginAdmin", admin);

            //合法, 重定向到manage.html
            //不使用请求转发?为了防止刷新页面会重复提交
            //这里为什么是写的 manage.html, 因为这样可以更加明确的表示到哪个页面
            //manage.html表示要去找 方法的映射路径为 manage.html
            return "redirect:/manage.html";
        } else {
            //不合法,就重新登录, 请求转发
            model.addAttribute("msg", "账号/用户错误");
            return "adminLogin";
        }
    }


    //处理用户的请求到 manage.html
    @GetMapping("/manage.html")
    public String mainPage(Model model, HttpSession session) {
		//是否登录。拦截器,过滤器
		Object loginAdmin = session.getAttribute("loginAdmin");
        
        if(loginAdmin != null){
        	return "manage";
        }else {
            //回到登录页面
            model.addAttribute("msg","请重新登录");
            return "login";
        }
    }
}

浏览器输入: http://localhost:8080/login

image-20230813205451060

image-20230813205550534

  1. 修改AdminController.java 模拟返回用户列表
//处理用户的请求到 manage.html
@GetMapping("/manage.html")
public String mainPage(Model model, HttpSession session) {
	Object loginAdmin = session.getAttribute("loginAdmin");
        if(null != loginAdmin) {//说明成功登录过
            //可以这里集合-模拟用户数据, 放入到request域中,并显示
            ArrayList<User> users = new ArrayList<>();
            users.add(new User(1, "关羽~", "666666", 20, "gy@sohu.com"));
            users.add(new User(2, "张飞", "666666", 30, "zf@sohu.com"));
            users.add(new User(3, "赵云", "666666", 22, "zy@sohu.com"));
            users.add(new User(4, "马超", "666666", 28, "mc@sohu.com"));
            users.add(new User(5, "黄忠", "666666", 50, "hz@sohu.com"));

            //将数据放入到request域
            model.addAttribute("users", users);

            return "manage"; //这里才是我们的视图解析到 /templates/manage.html
        } else {
            //这里就返回登录页,并给出提示
            model.addAttribute("msg","你没有登录/请登录");
            return "Login";
        }
}
  1. 修改manage.html , 显示用户列表
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理后台</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<a href='#'>返回管理界面</a>  <a href='#' th:href="@{/}">安全退出</a>   欢迎您:[[${session.loginAdmin.name}]]
<hr/>
<div style="text-align: center">
    <h1>管理雇员~</h1>
    <table border="1px" cellspacing="0" bordercolor="green" style="width:800px;margin: auto">
        <tr bgcolor="pink">
            <td>id</td>
            <td>name</td>
            <td>pwd</td>
            <td>email</td>
            <td>age</td>
        </tr>
        <tr bgcolor="#ffc0cb" th:each="user:${users}">
            <td th:text="${user.id}">a</td>
            <td th:text="${user.name}">b</td>
            <td th:text="${user.password}">c</td>
            <td th:text="${user.email}">d</td>
            <td th:text="${user.age}">e</td>
        </tr>
    </table>
    <br/>
</div>
<hr/>
<img src="images/logo.png"/>
</body>
</html>
  1. 修改login.html , 显示登录错误信息和提交action
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body bgcolor="#CED3FE">
<img src="images/1.GIF"/>
<hr/>
<div style="text-align: center">
    <h1>用户登陆</h1>
    <form action="#" th:action="@{/login}"  method="post">
        <label style="color: red" th:text="${msg}"></label><br/>
        用户名:<input type="text" style="width:150px" name="name"/><br/><br/>
        密 码:<input type="password" style="width:150px" name="password"/><br/><br/>
        <input type="submit" value="登录"/>
        <input type="reset" value="重新填写"/>
    </form>
</div>
<hr/>
<img src="images/logo.png"/>
</body>
</html>

完成测试

Thymeleaf 显示数据页面效果,浏览器: http://localhost:8080/login.html

image-20230813210208702
image-20230813210226052

😄总结

1、若要使用Thymeleaf 语法,首先要声明名称空间: xmlns:th=“http://www.thymeleaf.org”

2、设置文本内容th:text,设置input 的值th:value,循环输出th:each,条件判断th:if,插入代码块th:insert,定义代码块th:fragment,声明变量th:object

3、th:each 的用法需要格外注意,打个比方:如果你要循环一个div 中的p 标签,则th:each属性必须放在p 标签上。若你将th:each 属性放在div 上,则循环的是将整个div。

4、变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。

😁热门文章推荐

Thymeleaf快速入门及其注意事项

Spring Initailizr–快速入门–SpringBoot的选择

带你了解SpringBoot支持的复杂参数–自定义对象参数-自动封装

Rest 优雅的url请求处理风格及注意事项

文章到这里就结束了,如果有什么疑问的地方请指出,诸大佬们一起来评论区一起讨论😁
希望能和诸大佬们一起努力,今后我们一起观看感谢您的阅读🍻
如果帮助到您不妨3连支持一下,创造不易您们的支持是我的动力🤞

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/883500.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数据结构--最短路径 Floyd算法

数据结构–最短路径 Floyd算法 F l o y d 算法&#xff1a;求出每⼀对顶点之间的最短路径 \color{red}Floyd算法&#xff1a;求出每⼀对顶点之间的最短路径 Floyd算法&#xff1a;求出每⼀对顶点之间的最短路径 使⽤动态规划思想&#xff0c;将问题的求解分为多个阶段 对于n个顶…

re学习(31)BUUCTF-xx(多层加密)

参考文章&#xff1a;【BUUCTF逆向 [2019红帽杯]xx】_nb_What_DG的博客-CSDN博客 re学习笔记&#xff08;26&#xff09;BUUCTF-re-[2019红帽杯]xx_Forgo7ten的博客-CSDN博客 还有B站 水番正文 IDA64位载入 shiftF12查看字符串 交叉引用找到关键代码 使用findcrypt插件找到…

H13-922题库 HCIP-GaussDB-OLAP V1.5

**H13-922 V1.5 GaussDB(DWS) OLAP题库 华为认证GaussDB OLAP数据库高级工程师HCIP-GaussDB-OLAP V1.0自2019年10月18日起&#xff0c;正式在中国区发布。当前版本V1.5 考试前提&#xff1a; 掌握基本的数据库基础知识、掌握数据仓库运维的基础知识、掌握基本Linux运维知识、…

互联网发展历程:速度与效率,交换机的登场

互联网的演进就像一场追求速度与效率的竞赛&#xff0c;每一次的技术升级都为我们带来更快、更高效的网络体验。然而&#xff0c;在网络的初期阶段&#xff0c;人们面临着数据传输速度不够快的问题。一项关键的技术应运而生&#xff0c;那就是“交换机”。 速度不足的困境&…

SpringBoot + Mybatis多数据源

一、配置文件 spring: # datasource: # username: root # password: 123456 # url: jdbc:mysql://127.0.0.1:3306/jun01?characterEncodingutf-8&serverTimezoneUTC # driver-class-name: com.mysql.cj.jdbc.Driverdatasource:# 数据源1onedata:jdbc-url: j…

希尔排序【Java算法】

文章目录 1. 概念2. 思路3. 代码实现 1. 概念 希尔排序也是一种插入排序&#xff0c;它是简单插入排序经过改进之后的一个更高效的版本&#xff0c;也称为缩小增量排序。希尔排序在数组中采用跳跃式分组的策略&#xff0c;通过某个增量将数组元素划分为若干组&#xff0c;然后分…

linux学习(自写shell)[11]

打印出提示信息获取用户键盘输入 cmd_line[NUM];用来保存完整的命令行 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h>#define NUM 1024 char cmd_line[NUM]; //shell int main() {wh…

AI Chat 设计模式:15. 桥接模式

本文是该系列的第十五篇&#xff0c;采用问答式的方式展开&#xff0c;问题由我提出&#xff0c;答案由 Chat AI 作出&#xff0c;灰色背景的文字则主要是我的一些思考和补充。 问题列表 Q.1 如果你是第一次接触桥接模式&#xff0c;那么你会有哪些疑问呢&#xff1f;A.1Q.2 什…

FreeRTOS(独立看门狗监测任务执行与低功耗Tickless模式)

资料来源于硬件家园&#xff1a;资料汇总 - FreeRTOS实时操作系统课程(多任务管理) 目录 一、独立看门狗介绍 二、看门狗监测多任务执行思路 1、监测目标 2、监测方案 3、应用注意事项 三、看门狗监测多任务编程 1、STM32cubeMX配置 2、代码编写 四、低功耗Tickless模…

QT笔记——QProcess学习

我们常常想通过某一个类&#xff0c;来启动一个外部进程 本文将讲解如何通过QProcess来进行启动外部进程 一&#xff1a;了解QProcess QProcess是Qt框架提供的一个类&#xff0c;用于在应用程序中执行外部进程。它提供了一系列函数来启动、控制和与外部进程进行交互 1.启动进程…

02 基于51单片机的LED闪烁实验

目录 前言 一、整体目录结构 二、代码展示 三、main.c代码解析 四、下载到单片机中 总结 前言 前面我们已经学会了点亮一个led的实验&#xff0c;今天我们来实现LED闪烁。前面我们讲到想要让LED亮的话&#xff0c;只要给单片机引脚高电平就好了&#xff0c;如果给LED低电平的话…

Flink之Task解析

Flink之Task解析 对Flink的Task进行解析前,我们首先要清楚几个角色TaskManager、Slot、Task、Subtask、TaskChain分别是什么 角色注释TaskManager在Flink中TaskManager就是一个管理task的进程,每个节点只有一个TaskManagerSlotSlot就是TaskManager中的槽位,一个TaskManager中可…

Vue2-配置脚手架、分析脚手架、render函数、ref属性、props配置项、mixin配置项、scoped样式、插件

&#x1f954;:总有一段付出了没有回报的日子 是在扎根 更多Vue知识请点击——Vue.js VUE2-Day6 配置脚手架脚手架结构render函数vue.js与vue.runtime.xxx.js的区别引入render函数为什么要引入残缺的vue呢&#xff1f; 脚手架默认配置ref属性props配置项传递数据接收数据注意点…

elementui form组件出现英文提示

今天让解决一个bug&#xff0c;是表单组件提示词会出现英文。 问题情景如下&#xff1a; 有时会出现中文&#xff0c;有时会出现英文。 解决方法&#xff1a; 经查看&#xff0c;代码采用的是elementui的form组件&#xff0c;在el-form-item中使用了required属性&#xff0c;同…

企业权限管理(十)-用户详情

用户详情 UserController findById方法 Controller RequestMapping("/user") public class UserController {Autowiredprivate IUserService userService;//查询指定id的用户RequestMapping("/findById.do")public ModelAndView findById(String id) thro…

Python面向对象进阶教程,Python面向对象进阶知识笔记

类方法、静态方法 1. 类方法 第一个形参是类对象的方法需要用装饰器classmethod来标识其为类方法&#xff0c;对于类方法&#xff0c;第一个参数必须是类对象&#xff0c;一般以cls作为第一个参数。 class Dog(object): __type "狗" # 类方法&#xff0c;用class…

数据结构中公式前中后缀表达式-二叉树应用

目录 数据结构中公式前中后缀表达式-二叉树应用 数据结构中公式前中后缀表达式-二叉树应用 什么是前缀表达式、中缀表达式、后缀表达式 前缀表达式、中缀表达式、后缀表达式&#xff0c;是通过树来存储和计算表达式的三种不同方式 以如下公式为例 通过树来存储该公式&#x…

Avalonia 11 WebAssembly中文乱码

文章目录 0x00 原因0x01 解决方法FontForge 0x02 使用自定义字体App.axaml控件使用效果 0x00 原因 新建的Avalonia 11 WebAssembly项目&#xff0c;直接运行的话&#xff0c;会发现中文都是乱码&#xff0c;并且直接在控件上修改FontFamily属性是无法生效的。 0x01 解决方法…

MySQL学习笔记 - 进阶部分

MySQL进阶部分 字符集的相关操作&#xff1a;字符集和比较规则&#xff1a;utf8与utf8mb4&#xff1a;比较规则&#xff1a;常见的字符集和对应的Maxlen&#xff1a; Centos7中linux下配置字符集&#xff1a;各个级别的字符集&#xff1a;执行show variables like %character%语…

matlab画图中多个图例分开绘制

在matlab绘图中&#xff0c;线条较多时导致图例较长回遮挡原图/将图例分类&#xff0c;解决方案将图例分为多个。 一、多个图例一起显示 r 10; a 0; b 0; t0:0.1:2.1*pi; xar*cos(t); ybr*sin(t); plot(x,y,r,linewidth,4);hold on axis equal plot([0 0],[1 10],b,linewi…