Springboot项目实现用户登录与注册《mybatis-plus方式》<直观配图通俗易懂>

一.创建数据库表

CREATE TABLE `t_user` (
  `uid` int NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `username` varchar(20) NOT NULL COMMENT '用户名',
  `password` char(32) NOT NULL COMMENT '密码',
  `salt` char(36) DEFAULT NULL COMMENT '盐值',
  `phone` varchar(20) DEFAULT NULL COMMENT '电话号码',
  `email` varchar(30) DEFAULT NULL COMMENT '电子邮箱',
  `gender` int DEFAULT NULL COMMENT '性别:0-女,1-男',
  `avatar` varchar(50) DEFAULT NULL COMMENT '头像',
  `is_delete` int DEFAULT NULL COMMENT '是否删除:0-未删除,1-已删除',
  `created_user` varchar(20) DEFAULT NULL COMMENT '日志-创建人',
  `created_time` datetime DEFAULT NULL COMMENT '日志-创建时间',
  `modified_user` varchar(20) DEFAULT NULL COMMENT '日志-最后修改执行人',
  `modified_time` datetime DEFAULT NULL COMMENT '日志-最后修改时间',
  PRIMARY KEY (`uid`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb3;

二.添加pox依赖

    <!--mybatis-plus依赖  -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.1</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.4.1</version>
		</dependency>

	<!-- lombok依赖  -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
  
    <!--代码生成器所需代码依赖  -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-engine-core</artifactId>
			<version>2.2</version>
		</dependency>
   

    

三.mybatis-plus代码生成器生成基础代码框架,编写代码生成配置类  SggCodeGenertor--点击main方法执行

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
public class SggCodeGenerator {
    public static void main(String[] args) {
 
        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();
 
        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("玉面小白龙");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖
        gc.setServiceName("%sService");	//去掉Service接口的首字母I
        gc.setIdType(IdType.ID_WORKER_STR); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
 
        mpg.setGlobalConfig(gc);
 
        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/taobao?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
 
        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null); //模块名
        pc.setParent("com.xxx.admin");//自己的项目路径
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);
 
        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("t_user",);//对数据库那一张表生成代码
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
 
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
 
        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
 
        mpg.setStrategy(strategy);
 
        // 6、执行
        mpg.execute();
    }
}

3.1实例代码:xml文件我运动到了resources静态文件mapper文件夹下《本项目用不到xml》

四.application.yml--配置数据库连接:

server:
  port: 8888
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    #连接本地数据库
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
mybatis-plus:
  # mapper.xml 文件扫描
  mapper-locations: classpath*:/mapper/*.xml

五.编写统一返回数据类

 5.1结构展示:

public interface ResultCode {

    public static Integer SUCCESS = 20000; //成功

    public static Integer ERROR = 20001; //失败
}

import lombok.Data;
import java.util.HashMap;
import java.util.Map;

//统一返回结果的类
@Data
public class R {

    private Boolean success;//是否成功

    private Integer code;//返回码

    private String message;//返回消息

    private Map<String, Object> data = new HashMap<String, Object>();//返回数据

    //把构造方法私有
    private R() {}

    //成功静态方法
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }

    //失败静态方法
    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }
}

六.编写统一返回异常类:

public class ComFoundException extends RuntimeException {
    public ComFoundException() {
        super();
    }

    public ComFoundException(String message) {
        super(message);
    }

    public ComFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public ComFoundException(Throwable cause) {
        super(cause);
    }

    protected ComFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

七.编写注册+登录接口

1.TUserController层

@RestController
@RequestMapping("/t-user")
public class TUserController {

    @Autowired
    private TUserService tUserService;

    /**
     * 用户注册
     * @param
     * @return
     */
    @PostMapping("reg")
    public R reg(@RequestBody TUser tuser){
        tUserService.reg(tuser);
        return R.ok();
    }

    /**
     * 用户登录
     * @param
     * @return
     */
    @PostMapping("login")
    public R login(String username, String password){
        TUser login = tUserService.login(username,password);
        return R.ok().data("login",login);
    }
}

2.编写TUserService层方法

public interface TUserService extends IService<TUser> {
    /**
     * 用户注册
     * @param
     */
    void reg(TUser tuser);

    /**
     * 用户登录
     * @param  username 用户名
     * @param  password 用户密码
     * @return
     */
    TUser login(String username,String password);

}

八.TUserServiceIpml实现TUserService里面的方法

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.admin.common.ex.ComFoundException;
import com.xxx.admin.entity.TUser;
import com.xxx.admin.mapper.TUserMapper;
import com.xxx.admin.service.TUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;


@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;
    @Override
    public void reg(TUser tuser) {
        String username = tuser.getUsername();
        String password = tuser.getPassword();
        if (username==null || password==null){
            throw new ComFoundException("输入的用户名或密码不能为空");
        }
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        TUser tu =  tUserMapper.selectOne(queryWrapper);
        if (tu!=null){
            throw new ComFoundException("用户名已经被注册");
        }
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = getMd5(tuser.getPassword(), salt);
        tuser.setPassword(md5Password);
        tuser.setSalt(salt);
        tuser.setIsDelete(0);
       tuser.setCreatedUser(username);
        tuser.setCreatedTime(new Date());
        tuser.setModifiedUser(username);
        tuser.setModifiedTime(new Date());
        Integer rows = tUserMapper.insert(tuser);
        if (rows != 1) {
            throw new ComFoundException("添加数据失败");
        }

    }

  //md5加密规则
    private String getMd5(String password,String salt){
        for (int i = 0; i <3 ; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password +salt).getBytes()).toUpperCase();
        }
        return password;
    }


    @Override
    public TUser login(String username,String password) {
        if (username==null || password==null){
            throw new ComFoundException("输入账户或密码为空");
        }
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("is_delete",0);
        TUser t = tUserMapper.selectOne(queryWrapper);
        if (t==null){
            throw new ComFoundException("找不到用户信息");
        }
        String salt = t.getSalt();
        String md5Password = getMd5(password, salt);
        if (!t.getPassword().equals(md5Password)) {
            throw new ComFoundException("密码不正确");
        }
        TUser user = new TUser();
        user.setUid(t.getUid());
        user.setUsername(t.getUsername());
        user.setAvatar(t.getAvatar());
        return user;


    }
}

十.最后的测试就交给你们呐,推荐测试工具《Postman》:

直接到postman官网下载。下载后无需任何配置,安装好就可以直接使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值