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

简介: 该项目使用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编辑


目录
相关文章
|
4月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
531 2
|
10月前
|
存储 Java 数据库
Spring Boot 注册登录系统:问题总结与优化实践
在Spring Boot开发中,注册登录模块常面临数据库设计、密码加密、权限配置及用户体验等问题。本文以便利店销售系统为例,详细解析四大类问题:数据库字段约束(如默认值缺失)、密码加密(明文存储风险)、Spring Security配置(路径权限不当)以及表单交互(数据丢失与提示不足)。通过优化数据库结构、引入BCrypt加密、完善安全配置和改进用户交互,提供了一套全面的解决方案,助力开发者构建更 robust 的系统。
336 0
|
10月前
|
XML 前端开发 Java
SpringBoot实现文件上传下载功能
本文介绍了如何使用SpringBoot实现文件上传与下载功能,涵盖配置和代码实现。包括Maven依赖配置(如`spring-boot-starter-web`和`spring-boot-starter-thymeleaf`)、前端HTML页面设计、WebConfig路径映射配置、YAML文件路径设置,以及核心的文件上传(通过`MultipartFile`处理)和下载(利用`ResponseEntity`返回文件流)功能的Java代码实现。文章由Colorful_WP撰写,内容详实,适合开发者学习参考。
955 0
|
7月前
|
缓存 前端开发 Java
SpringBoot 实现动态菜单功能完整指南
本文介绍了一个动态菜单系统的实现方案,涵盖数据库设计、SpringBoot后端实现、Vue前端展示及权限控制等内容,适用于中后台系统的权限管理。
725 1
|
9月前
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
1143 8
|
8月前
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
1567 0
|
10月前
|
SQL 前端开发 Java
深入理解 Spring Boot 项目中的分页与排序功能
本文深入讲解了在Spring Boot项目中实现分页与排序功能的完整流程。通过实际案例,从Service层接口设计到Mapper层SQL动态生成,再到Controller层参数传递及前端页面交互,逐一剖析每个环节的核心逻辑与实现细节。重点包括分页计算、排序参数校验、动态SQL处理以及前后端联动,确保数据展示高效且安全。适合希望掌握分页排序实现原理的开发者参考学习。
654 4
|
10月前
|
存储 Java 定位技术
SpringBoot整合高德地图完成天气预报功能
本文介绍了如何在SpringBoot项目中整合高德地图API实现天气预报功能。从创建SpringBoot项目、配置依赖和申请高德地图API开始,详细讲解了实体类设计、服务层实现(调用高德地图API获取实时与预报天气数据)、控制器层接口开发以及定时任务的设置。通过示例代码,展示了如何获取并处理天气数据,最终提供实时天气与未来几天天气预报的接口。文章还提供了测试方法及运行步骤,帮助开发者快速上手并扩展功能。
|
12月前
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
4564 14

推荐镜像

更多