mybatis框架和spring框架整合实现登录功能详细代码
时间: 2024-10-28 13:10:29 浏览: 13
MyBatis和Spring框架整合是一个常见的企业级应用架构,它们分别处理持久层操作和业务逻辑管理。下面是一个简单的示例,展示了如何在Spring Boot项目中使用MyBatis进行用户登录功能的集成:
首先,你需要在pom.xml文件中添加MyBatis和Spring Boot的相关依赖:
```xml
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
version="2.4.5" <!-- 更新到最新版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 添加JDBC依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
然后配置MyBatis的SqlSessionFactory:
```java
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(MyBatisDataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean.getObject();
}
}
```
接下来,创建UserMapper接口并映射SQL查询:
```java
public interface UserMapper {
User findByUsername(String username);
}
```
在UserMapper.xml文件中编写SQL查询:
```xml
<mapper namespace="com.example.demo.UserMapper">
<select id="findByUsername" resultType="com.example.demo.User">
SELECT * FROM users WHERE username = #{username}
</select>
</mapper>
```
在Spring Security配置中检查用户名和密码:
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll() // 允许访问登录页面
.anyRequest().authenticated() // 非登录请求需要认证
.and()
.formLogin()
.loginPage("/login") // 设置登录页地址
.successHandler(customAuthenticationSuccessHandler())
.failureHandler(customAuthenticationFailureHandler());
}
@Bean
public AuthenticationProvider authenticationProvider() {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username -> userDetailsService.loadUserByUsername(username).orElse(null), null);
return new DaoAuthenticationProvider() {
@Override
protected Authentication authenticate(Authentication auth) throws AuthenticationException {
if (auth instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken usernamePasswordAuth = (UsernamePasswordAuthenticationToken) auth;
User user = userDetailsService.loadUserByUsername(usernamePasswordAuth.getPrincipal().toString()).orElse(null);
if (user != null && checkPassword(password, user.getPassword())) { // 使用自定义的密码校验逻辑
return usernamePasswordAuth;
} else {
throw new BadCredentialsException("Invalid credentials");
}
}
return null;
}
};
}
private boolean checkPassword(String password, String storedPassword) {
try {
// 这里可以调用UserMapper的findByUsername方法,传入数据库查询
UserMapper userMapper = sqlSession.selectOne(UserMapper.class, "username", "your_username_here");
return BCrypt.checkpw(password, userMapper.getPassword()); // 如果使用BCrypt库加密存储
} catch (Exception e) {
log.error("Error checking password", e);
return false;
}
}
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler() {
// 登录成功后的逻辑...
}
private CustomAuthenticationFailureHandler customAuthenticationFailureHandler() {
// 登录失败后的逻辑...
}
}
```
这只是一个基础示例,实际应用中还需要考虑异常处理、事务管理等细节,并且密码通常会通过加盐哈希的方式存储而不是明文。记住,
阅读全文