Spring Boot + Mybatis Plus实现登录注册
以下是一个简化的Spring Boot + MyBatis Plus实现登录注册功能的例子。
首先,你需要添加相关依赖到你的pom.xml
文件中:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Plus Starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.x.x</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
然后,配置数据库和MyBatis Plus:
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: your_username
password: your_password
mybatis-plus:
mapper-locations: classpath:/mappers/*.xml
type-aliases-package: com.yourpackage.model
创建用户实体和Mapper接口:
// User.java
@Data
public class User {
private Long id;
private String username;
private String password;
// 省略其他字段和getter/setter方法
}
// UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
// MyBatis Plus自动生成CRUD操作
}
实现登录和注册接口:
@RestController
public class AuthController {
@Autowired
private UserMapper userMapper;
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); // 注册时对密码进行加密
userMapper.insert(user);
return ResponseEntity.ok("注册成功");
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
User dbUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
if (dbUser == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
}
if (BCrypt.checkpw(user.getPassword(), dbUser.getPassword())) {
retur
评论已关闭