首页 > 其他分享 >springbootsecurity整合thymeleaf

springbootsecurity整合thymeleaf

时间:2024-07-29 20:26:58浏览次数:14  
标签:utf8mb3 -- sys thymeleaf springbootsecurity role 整合 VALUES NULL

首先创建一个springboot项目

然后加入相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wzy</groupId>
    <artifactId>springbootsecurity-thymeleaf02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootsecurity-thymeleaf02</name>
    <description>springbootsecurity-thymeleaf02</description>

    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

接着准备一个相应的数据库

/*
 Navicat Premium Data Transfer

 Source Server         : gz02
 Source Server Type    : MySQL
 Source Server Version : 80032
 Source Host           : localhost:3306
 Source Schema         : security

 Target Server Type    : MySQL
 Target Server Version : 80032
 File Encoding         : 65001

 Date: 24/11/2023 11:16:37
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission`  (
  `perid` int(0) NOT NULL AUTO_INCREMENT,
  `pername` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `percode` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`perid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES (1, '用户查询', 'user:query');
INSERT INTO `sys_permission` VALUES (2, '用户添加', 'user:add');
INSERT INTO `sys_permission` VALUES (3, '用户修改', 'user:update');
INSERT INTO `sys_permission` VALUES (4, '用户删除', 'user:delete');
INSERT INTO `sys_permission` VALUES (5, '用户导出', 'user:export');

-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role`  (
  `roleid` int(0) NOT NULL AUTO_INCREMENT,
  `rolename` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`roleid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES (1, '管理员');
INSERT INTO `sys_role` VALUES (2, '测试人员');
INSERT INTO `sys_role` VALUES (3, '普通用户');

-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission`  (
  `perid` int(0) NULL DEFAULT NULL,
  `roleid` int(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES (2, 1);
INSERT INTO `sys_role_permission` VALUES (1, 1);
INSERT INTO `sys_role_permission` VALUES (3, 1);
INSERT INTO `sys_role_permission` VALUES (4, 1);
INSERT INTO `sys_role_permission` VALUES (2, 2);
INSERT INTO `sys_role_permission` VALUES (1, 2);
INSERT INTO `sys_role_permission` VALUES (3, 2);
INSERT INTO `sys_role_permission` VALUES (1, 3);
INSERT INTO `sys_role_permission` VALUES (5, 3);

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user`  (
  `userid` int(0) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `userpwd` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`userid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES (1, '张三', '$2a$10$cI7e7bgSs9.9nNHhxKO9LuK/Ll.AeZwgUyZb77oD2y3UwwZyZhWG6', '男', '郑州');
INSERT INTO `sys_user` VALUES (2, '李四', '$2a$10$cI7e7bgSs9.9nNHhxKO9LuK/Ll.AeZwgUyZb77oD2y3UwwZyZhWG6', '男', '北京');
INSERT INTO `sys_user` VALUES (3, '王五', '$2a$10$cI7e7bgSs9.9nNHhxKO9LuK/Ll.AeZwgUyZb77oD2y3UwwZyZhWG6', '女', '杭州');

-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role`  (
  `userid` int(0) NOT NULL,
  `roleid` int(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES (1, 1);
INSERT INTO `sys_user_role` VALUES (2, 2);
INSERT INTO `sys_user_role` VALUES (3, 3);
INSERT INTO `sys_user_role` VALUES (1, 2);

SET FOREIGN_KEY_CHECKS = 1;
创建完成后需要在配置文件中连接相应的数据源


然后再创建service层

@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.nonNull(user)){
            List<Permission> permissions = permissionMapper.selectByPermission(user.getUserid());
            List<SimpleGrantedAuthority> collect = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(username,user.getUserpwd(),collect);
        }
        return null;
    }
}

注意这里要实现UserDetailsSercvice接口并实现其中的方法

接着就是Security的配置类

@Configuration//表示该类为配置类
public class MySecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailService userDetailService;
    @Bean//一定要加Bean注解,
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;
    }
//下下面自定义的页面
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .successForwardUrl("/success")
                .loginProcessingUrl("/login")
                .permitAll();
        http.csrf().disable();//表示禁用内置的csrf
        http.authorizeRequests().anyRequest().authenticated();//表示除了上方的路径其他都需要登入
        http.exceptionHandling().accessDeniedPage("/403.html");//权限不足跳转页面
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }
}

标签:utf8mb3,--,sys,thymeleaf,springbootsecurity,role,整合,VALUES,NULL
From: https://blog.csdn.net/wuzhaoyang11/article/details/140778945

相关文章

  • SSM整合Web工程报错Unable to locate Spring NamespaceHandler for XML schema namesp
    博主在启动Tomcat后报错这个 org.springframework.beans.factory.parsing.BeanDefinitionParsingException:Configurationproblem:UnabletolocateSpringNamespaceHandlerforXMLschemanamespace[http://www.springframework.org/schema/tx]Offendingresource:cl......
  • springboot整合mybatis
    第一部分:创建springboot文件 第一步:打开软件,点击file,点击new然后选择module,在右侧选择springboot第二步:选择配置和JDK以及java版本①选择maven类型②选择JDK1.8版本③选择java8版本④选择jar包类型http://t.csdnimg.cn/XeplRhttp://t.csdnimg.cn/XeplR第三步:选择......
  • springboot系列教程(二十二):springboot整合QuartJob,实现定时器实时管理
    一、QuartJob简介1、一句话描述Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大。2、核心API(1)、Scheduler代表一个Quartz的独立运行容器,Scheduler将Trigger绑定到特定JobDetail,这样当Trigger触发时,对应的Job就会被调度。(2)、Trigger描......
  • 搭建极狐GitLab(基于Docker): 步骤整合汇总记录
    执行背景:(1)CentOS7(虚拟机ISO映像文件=CentOS-7-x86_64-DVD-2009.iso);(2)repo(yum)源已切换为国内源;命令汇总:1.安装Docker相关命令:#查看仓库源中可使用版本yumlistdocker-ce--showduplicates|sort-r#安装指定版本yuminstalldocker-ce-docker完整......
  • SpringBoot入门实战:SpringBoot整合Shiro
    1.背景介绍SpringBoot是一个用于快速开发Spring应用程序的框架。它的核心是对Spring框架的一层封装,使其更加简单易用。SpringBoot整合Shiro是一种将SpringBoot与Shiro整合的方法,以实现身份验证和授权功能。Shiro是一个强大的Java安全框架,它提供了身份验证、授权、密码存......
  • Spring Boot + Spring Batch + Quartz 整合定时批量任务
     ​ 博客主页:   南来_北往系列专栏:SpringBoot实战前言最近一周,被借调到其他部门,赶一个紧急需求,需求内容如下:PC网页触发一条设备升级记录(下图),后台要定时批量设备更新。这里定时要用到Quartz,批量数据处理要用到SpringBatch,二者结合,可以完成该需求。由于之前,没有......
  • 3、springboot3 vue3开发平台-后端-swagger,knife4j整合
    文章目录1.knife4j简介2.引入依赖3.简单配置4.测试1.knife4j简介Knife4j是一个集Swagger2和OpenAPI3为一体的增强解决方案帮助开发者快速聚合使用OpenAPI规范。兼容OpenAPI3,使用更简介界面较swagger好看,文档导出、测试功能更简介方便官网:https://doc.......
  • Stable Diffusion整合包安装教程你值得拥有!!!(附安装包)
    Stabledifusion是一个开源的模型,开源=公开=免费,意味着你可以把这个模型下载到你自己的电脑上或者服务器上面畅玩没有审核人员卡你图片是否有问题,随意出图。01、电脑配置相关知识我们先来看看安装StableDiffusion整合包的需要的电脑配置:电脑配置需求:操作系统:windows......
  • SpringBoot Thymeleaf 模板标签
    扩展Thymeleaf模板标签上一篇我们写到SpringBoot依赖之Thymeleaf模版引擎的使用,当时只列举了简单文本标签,下面针对多标签进行分析和分享。Thymeleaf的模板标签,包括文本显示、属性设置、条件判断、循环迭代、表单处理、片段引用、国际化支持等常用功能。我们尽可能......
  • 植物大战僵尸杂交版v2.1整合包全解锁+高清工具
    植物大战僵尸杂交版v2.1整合包全解锁+高清工具 引言《植物大战僵尸》作为一款经典的塔防游戏,自2009年发布以来,就以其独特的游戏机制和幽默的风格赢得了全球玩家的喜爱。随着游戏的不断发展,开发者们也在不断探索新的玩法和元素,以保持游戏的新鲜感和吸引力。今天,我们要聊的就......