通用 普通 登录模块
# 通用普通登录模块
在实际生产环境中,登录功能需要具备良好的扩展性、可维护性,并且代码结构清晰易懂。以下是一个可直接用于生产环境的通用登录模块实现,代码中使用了 Hutool 工具类进行密码加密、数据校验等操作,方便后续扩展。
本方案包含以下部分:
- 数据库配置与用户实体类:
User - 数据传输对象:
LoginRequest和LoginResponse - 用户持久化层:
UserMapper和 MyBatis 配置 - 登录服务接口与实现:
LoginService和LoginServiceImpl - 全局异常处理:
GlobalExceptionHandler - 控制器层:
UserController - 登录成功后的响应封装
# 1. 数据库配置与用户实体类:User
说明:用户实体类对应数据库中的用户表,使用 MyBatis 进行持久化操作。示例中包含常见的用户信息字段,并可根据业务需求进行扩展。
# 数据库表设计(SQL):
CREATE TABLE `user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
`password` VARCHAR(100) NOT NULL COMMENT '密码,已加密',
`email` VARCHAR(100) DEFAULT NULL COMMENT '邮箱',
`phone` VARCHAR(20) DEFAULT NULL COMMENT '电话',
`status` TINYINT(1) DEFAULT 1 COMMENT '账户状态:1-启用,0-禁用',
`create_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 用户实体类:
import java.io.Serializable;
import java.util.Date;
/**
* @description 用户实体类,映射到数据库中的用户表
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String password;
private String email;
private String phone;
private Integer status;
private Date createTime;
private Date updateTime;
// Getters 和 Setters 省略,实际应用中需补充完整
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
重要 API 和参数说明:
- status:账户状态,
1表示启用,0表示禁用。 - password:保存加密后的密码,采用
Hutool进行加密。
# 2. 数据传输对象:LoginRequest 和 LoginResponse
说明:数据传输对象用于封装前端请求的数据和后端响应的数据。
# 登录请求 DTO:
/**
* @description 登录请求数据对象,用于封装前端传递的用户名和密码
*/
public class LoginRequest {
private String username;
private String password;
// Getters 和 Setters 省略,为了代码简洁,实际应用中需补充完整
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 登录响应 DTO:
/**
* @description 登录响应数据对象,用于封装登录成功后的用户信息
*/
public class LoginResponse {
private String username;
private String email;
private String phone;
// Getters 和 Setters 省略,为了代码简洁,实际应用中需补充完整
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
重要 API 和参数说明:
- LoginRequest:用于接收前端的用户名和密码。
- LoginResponse:用于返回登录成功后的用户信息。
# 3. 用户持久化层:UserMapper 和 MyBatis 配置
说明:使用 MyBatis 进行数据持久化操作,UserMapper 负责数据库的 CRUD 操作。
# MyBatis Mapper 接口:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* @description 用户持久化接口,定义数据库操作方法
*/
@Mapper
public interface UserMapper {
/**
* 根据用户名查询用户信息
*
* @param username 用户名
* @return 用户信息
*/
@Select("SELECT * FROM user WHERE username = #{username}")
User findByUsername(String username);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 4. 登录服务接口与实现:LoginService 和 LoginServiceImpl
说明:登录服务层负责处理用户认证和业务逻辑。
# 登录服务接口:
/**
* @description 登录服务接口,定义登录相关的方法
*/
public interface LoginService {
/**
* 用户登录验证
*
* @param loginRequest 登录请求对象
* @return 登录响应对象
*/
LoginResponse login(LoginRequest loginRequest);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 登录服务实现类:
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @description 登录服务实现类,处理用户登录逻辑
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private UserMapper userMapper;
@Override
public LoginResponse login(LoginRequest loginRequest) {
// 根据用户名查询用户信息
User user = userMapper.findByUsername(loginRequest.getUsername());
if (user == null || user.getStatus() == 0) {
throw new CustomException(ResultCode.FAILED, "用户不存在或已被禁用");
}
// 使用 Hutool 进行密码校验
String encryptedPassword = DigestUtil.md5Hex(loginRequest.getPassword());
if (!user.getPassword().equals(encryptedPassword)) {
throw new CustomException(ResultCode.VALIDATE_FAILED, "用户名或密码错误");
}
// 构建登录响应对象
LoginResponse response = new LoginResponse();
response.setUsername(user.getUsername());
response.setEmail(user.getEmail());
response.setPhone(user.getPhone());
return response;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
重要 API 和参数说明:
- DigestUtil.md5Hex(String input):使用 Hutool 的
md5Hex方法进行 MD5 加密。 - userMapper.findByUsername(String username):通过用户名查询用户信息。
# 5. 全局异常处理:GlobalExceptionHandler
说明:使用全局异常处理器统一捕获登录过程中可能抛出的自定义异常。
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @description 全局异常处理器,用于捕获登录模块中的异常
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public CommonResult<Object> handleCustomException(CustomException e) {
return CommonResult.custom(e.getResultCode(), e.getMessage());
}
@ExceptionHandler(Exception.class)
public CommonResult<Object> handleException(Exception e) {
e.printStackTrace();
return CommonResult.failed("系统异常,请稍后再试");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 6. 控制器层:UserController
说明:控制器层负责接收登录请求,并返回处理结果。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @description 用户控制器,处理登录请求
*/
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private LoginService loginService;
/**
* 登录接口
*
* @param loginRequest 登录请求对象
* @return 登录响应对象
*/
@PostMapping("/login")
public CommonResult<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
LoginResponse response = loginService.login(loginRequest);
return CommonResult.success(response);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
重要 API 和参数说明:
- @PostMapping("/login"):处理登录请求,返回
CommonResult<LoginResponse>。
# 7. 登录成功后的响应封装
# 登录成功返回示例:
{
"code": 200,
"message": "操作成功",
"data": {
"username": "admin",
"email": "admin@example.com",
"phone": "1234567890"
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 登录失败返回示例:
{
"code": 404,
"message": "用户名或密码错误",
"data": null
}
1
2
3
4
5
2
3
4
5
编辑此页 (opens new window)
上次更新: 2025/03/16, 22:19:39