【BackEnd】SpringBoot整合MongoDB实现登录注册功能(适合初学者)

本文涉及的产品
大数据开发治理平台 DataWorks,不限时长
实时数仓Hologres,5000CU*H 100GB 3个月
实时计算 Flink 版,5000CU*H 3个月
简介: 该项目使用SpringBoot2.7+MongoDB实现的登录注册Demo,可作为启动项目的BaseLine

  一、引言

作者将代码上传到了Gitee,小伙伴可以直接Clone项目到本地

项目地址:https://gitee.com/cai-zijing/SpringBoot_MongoDB_Login.git

再分享给大家一个非常好用的插件Gitee,主要功能为在IDEAL中与远程仓库进行可视化交互

image.gif编辑

输入项目地址一步解决项目克隆image.gif编辑

二、项目结构

image.gif编辑

三、代码

3.1 pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bcn</groupId>
    <artifactId>SpringBoot_MongoDB_Login</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot_MongoDB_Login</name>
    <description>SpringBoot_MongoDB_Login</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

image.gif

3.2 applicaiton.yml配置文件

因人喜好是否将application.propertie重命名为application.yml

server:
  port: 8900
  servlet:
    encoding:
      charset: utf-8
      enabled: true
spring:
  data:
    mongodb:
      uri: mongodb://root:123456@localhost:27017/login?maxIdleTimeMS=86400000
      port: 27017

image.gif

3.3 User实体类

@Data各个属性getter、setter等方法

@AllArgsConstructor有参构造函数

@NoArgsConstructor无参构造函数

@Document(collection = "user")对应数据库中的集合

package com.bcn.springboot_mongodb_login.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
 * @author 大白菜
 * @date Created in 2022/10/12 8:48
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "user")
public class User {
    @Id
    private String id;
    private String username;
    private String password;
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

image.gif

3.4 UserMapper接口层

@Repository SpringBoot数据访问层标志

MongoRepository<User,Long> 第一个参数User为对应实体类对象,Long为User的主键类型

MongoRepository是模板类,使用该类后很多方法可以直接获取,只需要定义好Restful风格函数名即可,类似于Mybatis_plus和JPA  

package com.bcn.springboot_mongodb_login.mapper;
import com.bcn.springboot_mongodb_login.pojo.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
 * @author 大白菜
 * @date Created in 2022/10/12 9:34
 */
@Repository
public interface UserMapper extends MongoRepository<User,String> {
    User findByUsername(String username);
}

image.gif

3.5 UserService业务接口层

当业务需求较为简单时,该层可舍弃,只用ServiceImpl即可

package com.bcn.springboot_mongodb_login.service;
import com.bcn.springboot_mongodb_login.pojo.User;
/**
 * @author 大白菜
 * @date Created in 2022/10/12 10:18
 */
public interface UserService {
    String loginService(String username,String password);
    String registerService(User user);
}

image.gif

3.6 UserServiceImpl业务层

@Service 业务层标志

package com.bcn.springboot_mongodb_login.service.Impl;
import com.bcn.springboot_mongodb_login.mapper.UserMapper;
import com.bcn.springboot_mongodb_login.pojo.User;
import com.bcn.springboot_mongodb_login.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
 * @author 大白菜
 * @date Created in 2022/10/12 10:19
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public String loginService(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return "用户不存在";
        } else {
            if (password.equals(user.getPassword())) {
                return "SUCCESS";
            } else {
                return "用户密码错误";
            }
        }
    }
    @Override
    public String registerService(User user) {
        String tempUnm = user.getUsername();
        User tempUser = userMapper.findByUsername(tempUnm);
        if (tempUser != null) {
            return "用户已存在";
        } else {
            userMapper.save(user);
            return "SUCCESS";
        }
    }
}

image.gif

3.7 UserController控制层

@SuppressWarnings({"all"}) 控制台输出过滤掉警告信息

@RestController控制层标志,等价于@Controller+@ResponseBody

@RequestMapping() 对外接口地址

package com.bcn.login_mybatis_demo.controller;
import com.bcn.login_mybatis_demo.pojo.User;
import com.bcn.login_mybatis_demo.service.serviceImpl.UserServiceImpl;
import com.bcn.login_mybatis_demo.util.Result;
import com.bcn.login_mybatis_demo.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author 大白菜
 * @date Created in 2022/9/26 14:56
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServiceImpl userServiceImpl;
    @RequestMapping("/login")
    public Result login(@RequestParam String uact, @RequestParam String upwd) {
        String msg = userServiceImpl.loginService(uact,upwd);
        if(("SUCCESS").equals(msg)){
            return ResultUtil.success("登录成功");
        }else{
            return ResultUtil.error(msg);
        }
    }
    @RequestMapping("/register")
    public Result login(@RequestBody User user) {
        String msg = userServiceImpl.registerService(user);
        if(("SUCCESS").equals(msg)){
            return ResultUtil.success("注册成功");
        }else{
            return ResultUtil.error(msg);
        }
    }
}

image.gif

3.8 Result、ResultCode、ResultUtil 返回结果工具类

在正式开发中,我们返回给前端除了Body之外,还需要状态码与状态信息,这就需要使用到Result工具类,其返回效果如下

image.gif编辑

Result类

package com.bcn.springboot_mongodb_login.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:54
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    private Integer code;
    private String msg;
    private T data;
}

image.gif

ResultCode类

package com.bcn.springboot_mongodb_login.util;
/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:50
 */
public enum ResultCode {
    // 自定义枚举内容
    SUCCESS(200, "Success"),
    ERROR(400, "Error");
    private Integer code;
    private String msg;
    ResultCode(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Integer getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
}

image.gif

ResultUtil类

package com.bcn.springboot_mongodb_login.util;
/**
 * @author 大白菜
 * @date Created in 2022/9/26 19:55
 */
public class ResultUtil {
    /**
     * 成功且带数据
     **/
    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(object);
        return result;
    }
    /**
     * 成功但不带数据
     **/
    public static Result success() {
        return success(null);
    }
    /**
     * 失败
     **/
    public static Result error(Object object) {
        Result result = new Result();
        result.setCode(ResultCode.ERROR.getCode());
        result.setMsg(ResultCode.ERROR.getMsg());
        result.setData(object);
        return result;
    }
}

image.gif

3.9 login.js数据库文件

/*
 Navicat Premium Data Transfer
 Source Server         : Demo
 Source Server Type    : MongoDB
 Source Server Version : 60001 (6.0.1)
 Source Host           : localhost:27017
 Source Schema         : login
 Target Server Type    : MongoDB
 Target Server Version : 60001 (6.0.1)
 File Encoding         : 65001
 Date: 12/10/2022 11:05:31
*/
// ----------------------------
// Collection structure for user
// ----------------------------
db.getCollection("user").drop();
db.createCollection("user");
// ----------------------------
// Documents of user
// ----------------------------
db.getCollection("user").insert([ {
    _id: ObjectId("634617c49d110f9df6014f83"),
    username: "bcn",
    password: "123"
} ]);
db.getCollection("user").insert([ {
    _id: ObjectId("634618219d110f9df6014f85"),
    username: "alg",
    password: 123
} ]);
db.getCollection("user").insert([ {
    _id: ObjectId("63462e5c39561e5497cfd4bf"),
    username: "aaa",
    password: "123",
    _class: "com.bcn.springboot_mongodb_login.pojo.User"
} ]);

image.gif

接口测试

image.gif编辑

image.gif编辑


相关实践学习
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
15天前
|
存储 NoSQL Java
大事件后端项目34_登录优化----redis_SpringBoot集成redis
大事件后端项目34_登录优化----redis_SpringBoot集成redis
大事件后端项目34_登录优化----redis_SpringBoot集成redis
|
3天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的多功能智能手机阅读APP的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的多功能智能手机阅读APP的详细设计和实现(源码+lw+部署文档+讲解等)
|
6天前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的多功能智能手机阅读APP附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的多功能智能手机阅读APP附带文章源码部署视频讲解等
10 1
|
11天前
|
NoSQL Java MongoDB
Spring Boot与MongoDB的集成应用
Spring Boot与MongoDB的集成应用
|
14天前
|
SQL XML JavaScript
【若依Java】15分钟玩转若依二次开发,新手小白半小时实现前后端分离项目,springboot+vue3+Element Plus+vite实现Java项目和管理后台网站功能
摘要: 本文档详细介绍了如何使用若依框架快速搭建一个基于SpringBoot和Vue3的前后端分离的Java管理后台。教程涵盖了技术点、准备工作、启动项目、自动生成代码、数据库配置、菜单管理、代码下载和导入、自定义主题样式、代码生成、启动Vue3项目、修改代码、以及对代码进行自定义和扩展,例如单表和主子表的代码生成、树形表的实现、商品列表和分类列表的改造等。整个过程详细地指导了如何从下载项目到配置数据库,再到生成Java和Vue3代码,最后实现前后端的运行和功能定制。此外,还提供了关于软件安装、环境变量配置和代码自动生成的注意事项。
119 2
|
6天前
|
存储 NoSQL Java
使用Spring Boot和MongoDB构建NoSQL应用
使用Spring Boot和MongoDB构建NoSQL应用
|
10天前
|
存储 Java
软件开发常用之SpringBoot文件上传接口编写(中),一本书,代码大全(里面有很多代码重构的方法),屎山代码的原因是不断追加逻辑,在错误代码上堆积新的功能,在写完逻辑之后去思考一下,逻辑合理不
软件开发常用之SpringBoot文件上传接口编写(中),一本书,代码大全(里面有很多代码重构的方法),屎山代码的原因是不断追加逻辑,在错误代码上堆积新的功能,在写完逻辑之后去思考一下,逻辑合理不
|
10天前
|
Java 文件存储
软件开发常用之SpringBoot文件上传和下载功能(上){fileName},利用hutool提供的依赖,拿到当前目录的路径,System.getProperty从变量获取路径 ,不存在就用mkdi
软件开发常用之SpringBoot文件上传和下载功能(上){fileName},利用hutool提供的依赖,拿到当前目录的路径,System.getProperty从变量获取路径 ,不存在就用mkdi
|
14天前
|
NoSQL Java MongoDB
如何在Spring Boot应用中集成MongoDB数据库
如何在Spring Boot应用中集成MongoDB数据库
|
14天前
|
Java API Spring
Spring Boot中如何实现邮件发送功能
Spring Boot中如何实现邮件发送功能