SpringBoot整合SpringSecurity+Mybatis实现自定义登录

本文介绍了如何在SpringBoot应用中整合SpringSecurity和Mybatis,实现一个自定义登录页面。配置包括Maven依赖、Mysql连接、数据接口及实体类、服务和控制类。在SpringSecurity部分,涉及认证处理类、认证成功处理类和配置类的设置。前端登录页实现需注意表单提交的URL和方式,以匹配Security配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件配置

本文实现的是一个简单的自定义登录页,所以只需要配置Mysql即可

Maven配置

因为需要使用到Mysql和MyBatis所以需要添加相关的依赖

 <dependencies>
 	   <!-- 添加Spring Security依赖-->
 	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--添加mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
		<!--添加Mysql连接依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
 </dependencies>

Mysql相关的配置

在application.properties中配置Mysql()

// An highlighted block
spring.datasource.url=jdbc:mysql://localhost:3306/blogrepository?useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

通过上面的配置即可配置好Mysql,需要注意的时,新版本的Mysql在连接时需要指定UTC时区,通过serverTimeZone=GMT来指定。否则会出现下面的异常报错:
Java.sql.SQLException: The server time zone value ‘…???’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

数据接口的实现

数据表

id username passwd
1 root root

数据表对应的实体类

@Component
public class User implements Serializable {
   
    private static final long serialVersionUID = 1L;

    private int id;
    private String username;
    private String passwd;

    public int getId() {
   
        return id;
    }

    public void setId(int id) {
   
        this.id = id;
    }

    public String getUsername() {
   
        return username;
    }

    public void setUsername(String username) {
   
        this.username = username;
    }

    public String getPasswd() {
   
        return passwd;
    }

    public void setPasswd(String passwd) {
   
        this.passwd = passwd;
    }
}

数据访问类

通过Mybatis的注解来实现数据库的访问

@Mapper
@Repository
public interface UserMapper {
   
    @Select("select id,username,passwd from user"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值