记住我-数据库版(不重要)

开始吧

为了让服务器重启也不影响记住登录状态,将用户登录状态信息存入数据库。

1、 添加数据库依赖

  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.22</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>

2、 创建数据库

CREATE DATABASE `SpringSecurity_Demo` CHARACTER SET utf8; 

3、 建立数据库连接的配置

我自己有创建了一个spring的配置文件:spring.xml


    <!--配置数据源:用来连接数据库的-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/security?useSSL=false"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>

    <!--jdbcTemplate:用来操作数据库的-->
    <bean class="org.springframework.jdbc.core.JdbcTemplate" name="jdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

如果要服务器启动读取到spring.xml文件,还要配置web.xml给出配置文件的监听器。

···xml


contextConfigLocation
classpath:spring.xml



org.springframework.web.context.ContextLoaderListener


## 4、 在自己写的配置类SpringSecurityConfig中注入数据源

```java
  //数据源
  @Autowired
  private DataSource dataSource;

5、 启用令牌仓库

这也让我get知识点:对象不能再成员位置new

//重写configure方法进行配置
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

    //启用令牌仓库
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);
    
    ......
}

6、 建SpringSecurity登录规定的相应的表

注意:需要进入 JdbcTokenRepositoryImpl 类中找到创建 persistent_logins 表的 SQL 语句创建

CREATE TABLE `persistent_logins` (
  `username` varchar(64) NOT NULL,
  `series` varchar(64) NOT NULL,
  `token` varchar(64) NOT NULL,
  `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
posted @ 2020-11-08 01:44  我才不是你的谁  阅读(73)  评论(0编辑  收藏  举报