【SpringSecurity】七、SpringSecurity集成thymeleaf

这篇具有很好参考价值的文章主要介绍了【SpringSecurity】七、SpringSecurity集成thymeleaf。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

1、thymeleaf

查了下读音,leaf/li:f/,叶子,前面的单词发音和时间time一样。

  • 官网:https://www.thymeleaf.org/
  • 参考中文文档:https://fanlychie.github.io/post/thymeleaf.html

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

即Thymeleaf是适用于Web和独立环境的现代服务器端Java 模板引擎 。模板引擎的作用就是使用户界面与业务数据(内容)分离,就是做好一个模板后套入对应位置的数据,最终以html的格式展示出来。知乎上有个很形象的例子:

=======================================================
【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

简单说就是,没模板引擎,就像高中操场开会,桌子、板凳、场地都要现搬现搭。而模板引擎的作用就像大学开会,有专门会议室,板凳桌子设备都准备好了,今天学院A进来用了,明天学院B进来用了,学院A、B就像数据。

将模板设计好之后直接填充数据即可而不需要重新设计整个页面,开箱即用,提高页面、代码的复用性。

市面上开源的第三方的模板引擎也比较多,有Thymeleaf、FreeMaker、Velocity等

2、依赖部分

引入thymeleaf依赖:

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

当然如果是新创建项目,直接勾选热门依赖就行:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

修改配置文件:

spring:
  thymeleaf:
    cache: false # 开发阶段可以先不使用缓存
	check-template: true  # 检查thymeleaf模板是否存在

之所以不使用缓存,是为了临时有改动时,点一下小锤子就能看效果:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf
在IDEA添加thymeleaf文件模板,方便以后使用:File-Setting

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

模板名称thymeleaf ,扩展名html,内容如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>#[[$Title$]]#</title>        
</head>
<body>
#[[$END$]]#
</body>
</html>

PS:
#[[$Title$]]# #[[$END$]]# 这两处的作用是:
当你新建一个模板页面时,在<title>标签中输入标题内容后,只需要点击回车键,光标就会直接跳到<body>内,省去了你挪动鼠标,或者挪动方向键的步骤,也可以给你节省一点点时间。

也可在IDEA中安装html转thymeleaf的插件:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

3、定义Controller

//这里别用RestController了,不再返回一个json对象或者普通字符串了
@Controller  
@RequestMapping("/login")
public class LoginController {
    /**
     * 跳转到登陆页面
     */
    @RequestMapping("/toLogin")    //GET、POST都行的意思
    public String toLogin(){
        return "login";
    }

}

上面的这个return "login"字符串,是返回thymeleaf的逻辑视图名,物理视图 = 前缀 + 逻辑视图 + 后缀,即/templates/ + login + .html(点住application.yaml文件中thymeleaf的配置查看源码:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

再定义登录成功后进入主页的controller,返回逻辑视图名main(随便起的):

@Controller
@RequestMapping("/index")
public class IndexController {

    /**
     * 登录成功后进入主页
     */
    @RequestMapping("/toIndex")
    public String toIndex(){
        return "main";
    }
}

4、创建静态页面

templates下面创建login.html和main.html:(放到类路径中的resource下面)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户登陆</title>
</head>
<body>
<h2>登录页面</h2>
<form action="/login/doLogin" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="uname" value="thomas"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="pwd"></td>
            <span th:if="${param.error}">用户名或者密码错误</span>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>

mian.html内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统首页</title>
</head>
<body>
<h1 align="center">系统首页</h1>
<a href="/student/query">查询学生</a>
<br>
<a href="/student/add">添加学生</a>
<br>
<a href="/student/update">更新学生</a>
<br>
<a href="/student/delete">删除学生</a>
<br>
<a href="/student/export">导出学生</a>
<br>
<br><br><br>
<h2><a href="/logout">退出</a></h2>
<br>
</body>
</html>

5、WebSecurityConfigurerAdapter

修改安全配置类:

@EnableGlobalMethodSecurity(prePostEnabled = true)
//@Configuration
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	//编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置登陆方式
        http.formLogin()//使用用户名和密码的登陆方式
                .usernameParameter("uname") //页面表单的用户名的name,上面login.html中定义的用户名的参数名
                .passwordParameter("pwd")//页面表单的密码的password,上面login.html中定义的密码的参数名
                .loginPage("/login/toLogin") //自己定义登陆页面的地址
                .loginProcessingUrl("/login/doLogin")//配置登陆的url
                .successForwardUrl("/index/toIndex") //登陆成功跳转的页面,成功跳首页
                .failureForwardUrl("/login/toLogin")//登陆失败跳转的页面,失败跳登录页
                .permitAll();
        //配置退出方式
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login/toLogin")
                .permitAll();
        //配置路径拦截 的url的匹配规则
        http.authorizeRequests()
                //任何路径要求必须认证之后才能访问
                .anyRequest().authenticated();
        // 先禁用csrf跨站请求攻击保护  后面可以使用postman工具测试,注意要禁用csrf
        http.csrf().disable();
    }
}

此时登录后可以跳转首页了:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

6、权限相关

修改上一篇中的StudentController,写接口,返回不同的逻辑视图名称字符串。并给接口加权限校验。

@Controller   //返回的不是一个字符串,是一个视图名
@Slf4j
@RequestMapping("/student")
public class StudentController {
    @GetMapping("/query")
    @PreAuthorize("hasAuthority('student:query')")
    public String queryInfo(){
        return "user/query";   //:templates/ + user/query + .html    }
    @GetMapping("/add")
    @PreAuthorize("hasAuthority('student:add')")
    public String addInfo(){
        return "user/add";
    }
    @GetMapping("/update")
    @PreAuthorize("hasAuthority('student:update')")
    public String updateInfo(){
        return "user/update";
    }
    @GetMapping("/delete")
    @PreAuthorize("hasAuthority('student:delete')")
    public String deleteInfo(){
        return "user/delete";
    }
    @GetMapping("/export")
    @PreAuthorize("hasAuthority('student:export')")
    public String exportInfo(){
        return "/user/export";
    }
}

在templates/user下面创建学生管理的各个页面,export.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>系统首页-学生管理</title>
</head>
<body>
<h1 align="center">系统首页-学生管理-导出</h1>
<a href="/index/toIndex">返回</a>
<br>
</body>
</html>

add.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统首页-学生管理</title>
</head>
<body>
<h1 align="center">系统首页-学生管理-新增</h1>
<a href="/index/toIndex">返回</a>
<br>
</body>
</html>

update.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统首页-学生管理</title>
</head>
<body>
<h1 align="center">系统首页-学生管理-更新</h1>
<a href="/index/toIndex">返回</a>
<br>
</body>
</html>

delete.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统首页-学生管理</title>
</head>
<body>
<h1 align="center">系统首页-学生管理-删除</h1>
<a href="/index/toIndex">返回</a>
<br>
</body>
</html>

query.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统首页-学生管理</title>
</head>
<body>
<h1 align="center">系统首页-学生管理-查询</h1>
<a href="/index/toIndex">返回</a>
<br>
</body>
</html>

在static/error下面创建403.html,当没有权限的时候,就会使用这里的403页面代替框架自带的403页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>403</title>
</head>
<body>
<h2>403:你没有权限访问此页面</h2>
<a href="/index/toIndex">去首页</a>
</body>
</html>

查看效果:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf

7、当用户没有某权限时,页面不展示该按钮

当用户点击页面上的链接请求到后台之后没有权限会跳转到403,那么如果用户没有权限,对应的按钮就不显示出来,这样岂不是更好吗。下面开始实现:

  • 引入依赖
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

  • 修改首页代码,在标签的sec属性中加入对应的所需权限
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>系统首页</title>
</head>
<body>
<h1 align="center">系统首页</h1>
<a href="/student/query" sec:authorize="hasAuthority('student:query')" >查询用户</a>
<br>
<a href="/student/add" sec:authorize="hasAuthority('student:save')" >添加用户</a>
<br>
<a href="/student/update" sec:authorize="hasAuthority('student:update')" >更新用户</a>
<br>
<a href="/student/delete" sec:authorize="hasAuthority('student:delete')" >删除用户</a>
<br>
<a href="/student/export" sec:authorize="hasAuthority('student:export')" >导出用户</a>
<br>
<br><br><br>
<h2><a href="/logout">退出</a></h2>
<br>
</body>
</html>


重启,此时的效果:

【SpringSecurity】七、SpringSecurity集成thymeleaf,SpringSecurity,SpringSecurity,模板引擎,thymeleaf文章来源地址https://www.toymoban.com/news/detail-697538.html

到了这里,关于【SpringSecurity】七、SpringSecurity集成thymeleaf的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot整合模板引擎Thymeleaf(4)

    本文原创作者:谷哥的小弟 作者博客地址:http://blog.csdn.net/lfdfhl 在之前的教程中,我们介绍了Thymeleaf的基础知识。在此,以案例形式详细介绍Thymeleaf的基本使用。 要点概述: 1、在static下创建css文件夹用于存放css文件 2、在static下创建img文件夹用于存放图片文件 请在pom.xml文

    2024年02月10日
    浏览(34)
  • 前端模板引擎Thymeleaf的整合和使用

    目录 一、添加依赖 1.1首先,在项目的构建文件中(比如 Maven 或 Gradle)添加 Thymeleaf 的依赖。例如,对于 Maven 项目,在 pom.xml 文件中添加以下依赖 1.2保存并更新项目依赖 二、配置Thymeleaf 2.1模板位置配置 2.2模板缓存配置 2.3自定义标签配置 三、创建模板文件 3.1创建一个HTML文

    2024年04月27日
    浏览(46)
  • 【SpringBoot学习笔记】04. Thymeleaf模板引擎

     所有的html元素都可以被thymeleaf替换接管  th:元素名 templates下的只能通过Controller来跳转,templates前后端分离,需要模板引擎thymeleaf支持    模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封

    2024年02月13日
    浏览(27)
  • SpringBoot自带模板引擎Thymeleaf使用详解①

    目录 前言 一、SpringBoot静态资源相关目录 二、变量输出 2.1 在templates目录下创建视图index.html 2.2 创建对应的Controller 2.3 在视图展示model中的值 三、操作字符串和时间 3.1 操作字符串 3.2 操作时间         Thymeleaf是一款用于渲染XML/HTML5内容的模板引擎,类似JSP。它可以轻易的

    2024年02月08日
    浏览(31)
  • SpringBoot自带模板引擎Thymeleaf使用详解②

    目录 一、条件判断和迭代遍历 1.1 条件判断 2.2 迭代遍历 二、获取域中的数据和URL写法 2.1 获取域中的数据 2.2 URL写法 三、相关配置 语法 作用 th:if 条件判断 准备数据 model.addAttribute(\\\"sex\\\",\\\"男\\\"); 使用实例 div     span th:if=\\\"${sex}==\\\'女\\\'\\\"这是女生/span     span th:if=\\\"${sex}==\\\'男\\\'\\\"这是男

    2024年02月08日
    浏览(28)
  • 15 springboot项目——thymeleaf语法与关闭模板引擎

            在html文件中,有些是需要使用本地的css样式,使用thymeleaf语法加载:         首先对head标签上面的html标签进行更改:         其次,导入thymeleaf依赖:         接着,使用thymeleaf语法:         碰到href或者src后边与静态资源有关的的本地路径要进行修改,把要

    2024年02月14日
    浏览(30)
  • 【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

    🌕博客x主页:己不由心王道长🌕! 🌎文章说明:spring🌎 ✅系列专栏:spring 🌴本篇内容:对SpringBoot进行一个入门学习及对Thymeleaf模板引擎进行整合(对所需知识点进行选择阅读呀~)🌴 ☕️每日一语:在人生的道路上,即使一切都失去了,只要一息尚存,你就没有丝毫理

    2023年04月23日
    浏览(33)
  • 【Spring Boot】Thymeleaf模板引擎 — 表达式的语法

    模板的主要作用是将后台返回的数据渲染到HTML中。那么Thymeleaf是如何解析后台数据的呢?接下来从变量、方法、条件判断、循环、运算(逻辑运算、布尔运算、比较运算、条件运算)方面学习Thymeleaf表达式支持的语法。 (1)文本赋值 赋值就是通过${}标签将后台返回的数据替

    2024年02月14日
    浏览(27)
  • Thymeleaf模版引擎初尝试

    模版引擎虽然不能够实现代码与视图解耦,但是其适合于个人开发者使用,而且如果存在前后端项目中,前端大量请求后端时,模版引擎无疑也存在优势。 SpringBoot 整合步骤: 引入依赖 编写 yml 配置 编写 html 模版文件 编写 Controller 接口

    2024年02月13日
    浏览(32)
  • Thymeleaf SSTI模板注入分析

    先搭建一个SpringMVC项目,参考这篇文章,或者参考我以前的spring内存马分析那篇文章 https://blog.csdn.net/weixin_65287123/article/details/136648903 简单写个servlet 这样就是访问到index.jsp 路由解析流程主要就是 Model 和 View 以及最后 Render 。return处打个断点,看怎么处理的 先进入 invokeAndHa

    2024年04月12日
    浏览(20)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包