企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**1. `application.yml`配置数据库信息** ```yml spring: datasource: username: root password: uhg</flEt3dff url: jdbc:mysql://localhost:3306/learndb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver ``` **2. 配置数据源** ```java @Configuration public class BrowserSecurityConfig { @Autowired private DataSource dataSource; @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl(); jdbcTokenRepository.setDataSource(dataSource); //首次启动时Spring Security需要自动建persistent_logins表,请将设置为true,建表后将其设置为false jdbcTokenRepository.setCreateTableOnStartup(false); return jdbcTokenRepository; } } ``` **3. 开启记住我功能** ```java @Configuration @RequiredArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { final LoginServiceImpl loginService; final PersistentTokenRepository tokenRepository; @Override protected void configure(HttpSecurity http) throws Exception { //开启记住我功能 http.rememberMe() //有效期,如果不设置默认为2周,单位为s .tokenValiditySeconds(3600) .tokenRepository(tokenRepository) .userDetailsService(loginService); } } ``` **4. 登录表单** ```html <form action="/login" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"/><br/> <!-- 记住我的name必须为remember-me --> 记住我:<input type="checkbox"name="remember-me"title="记住密码"/><br/> <input type="submit" value="提交"/> </form> ``` **5. 测试** 经测试,一个账号登录后,关闭浏览器再打开浏览器访问不再需要登录,配置成功了。