程序员scholar 程序员scholar
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Python 基础

    • Python基础
  • Python 进阶

    • 装饰器与生成器
    • 异常处理
    • 标准库精讲
    • 模块与包
    • pip包管理工具
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
前端 (opens new window)
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Python 基础

    • Python基础
  • Python 进阶

    • 装饰器与生成器
    • 异常处理
    • 标准库精讲
    • 模块与包
    • pip包管理工具
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
前端 (opens new window)
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
npm

(进入注册为作者充电)

  • 后端开发

    • Spring Boot多模块项目开发
    • Spring Boot图片资源返回
    • Spring Boot文件上传
    • Spring Boot文件下载
    • 对接第三方文件上传
    • Servlet 原生API
    • HttpServletResponse 和 ResponseEntity
    • 后端解决跨域问题
    • 后端拦截器
    • SpringBoot+Vue实现邮件发送与验证码验证
    • 谷歌验证码
    • 利用hutool工具类实现图片验证码
    • 统一返回格式
    • 通用 普通 登录模块
      • 1. 数据库配置与用户实体类:User
        • 数据库表设计(SQL):
        • 用户实体类:
      • 2. 数据传输对象:LoginRequest 和 LoginResponse
        • 登录请求 DTO:
        • 登录响应 DTO:
      • 3. 用户持久化层:UserMapper 和 MyBatis 配置
        • MyBatis Mapper 接口:
      • 4. 登录服务接口与实现:LoginService 和 LoginServiceImpl
        • 登录服务接口:
        • 登录服务实现类:
      • 5. 全局异常处理:GlobalExceptionHandler
      • 6. 控制器层:UserController
      • 7. 登录成功后的响应封装
        • 登录成功返回示例:
        • 登录失败返回示例:
    • 通用 JWT 登录认证模块
    • 通用 普通 注册模块
    • 基于 MyBatis curd
    • 基于 MyBatis-Plus curd
    • Java 常见对象模型
    • 开发枚举的使用
    • MyBatis与MyBatis-Plus日期类型处理
    • 接口日志拦截基础版
    • 接口日志拦截进阶版
    • 文件操作工具类
    • Spring Boot 数据校验
    • 幂等性
  • 前端开发

  • 开发笔记
  • 后端开发
scholar
2024-12-27
目录

通用 普通 登录模块

# 通用普通登录模块

在实际生产环境中,登录功能需要具备良好的扩展性、可维护性,并且代码结构清晰易懂。以下是一个可直接用于生产环境的通用登录模块实现,代码中使用了 Hutool 工具类进行密码加密、数据校验等操作,方便后续扩展。

本方案包含以下部分:

  1. 数据库配置与用户实体类:User
  2. 数据传输对象:LoginRequest 和 LoginResponse
  3. 用户持久化层:UserMapper 和 MyBatis 配置
  4. 登录服务接口与实现:LoginService 和 LoginServiceImpl
  5. 全局异常处理:GlobalExceptionHandler
  6. 控制器层:UserController
  7. 登录成功后的响应封装

# 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

# 用户实体类:

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

重要 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

# 登录响应 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

重要 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

# 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

# 登录服务实现类:

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

重要 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

# 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

重要 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

# 登录失败返回示例:

{
  "code": 404,
  "message": "用户名或密码错误",
  "data": null
}
1
2
3
4
5

编辑此页 (opens new window)
上次更新: 2025/03/16, 22:19:39
统一返回格式
通用 JWT 登录认证模块

← 统一返回格式 通用 JWT 登录认证模块→

Theme by Vdoing | Copyright © 2019-2025 程序员scholar
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式