SpringBoot:一个简约的网盘系统之注册登录

1. 首页

image

1.1 注册页面

image

1.2 登录页面

image

2. 注册/登录
2.1 新建UserMapper.java(与用户相关的数据库操作接口)
package com.beyond.disk.mapper;

import com.beyond.disk.pojo.User;
import org.apache.ibatis.annotations.Mapper;


/**
 * @author Beyond
 * @Description: 与用户相关的数据库操作接口
 * @date 2021/5/29 22:49
 */
@Mapper
public interface UserMapper {
    /**
    * @Description: 新增用户
    * @param user 实例对象
    * @return 0,1
    * @author Beyond
    * @date 2021/5/29 22:54
    */
    int insert(User user);

    /**
     * @Description: 通过邮箱查询单条数据
     * @param email 邮箱
     * @return 实例对象
     * @author Beyond
     * @date 2021/5/29 22:56
     */
    User queryUserByEmail(String email);

    /**
    * @Description: 通过邮箱和密码查询单条数据
    * @param email 邮箱
    * @param password 密码
    * @return 实例对象
    * @author Beyond
    * @date 2021/5/29 22:58
    */
    User queryByEmailAndPwd(String email, String password);

}

2.2 新建UserMapper.xml(Mybatis的sql文件)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.beyond.disk.mapper.UserMapper">

    <!--user的映射结果集-->
    <resultMap type="com.beyond.disk.pojo.User" id="UserMap">
        <result property="userId" column="user_id" jdbcType="INTEGER"/>
        <result property="openId" column="open_id" jdbcType="VARCHAR"/>
        <result property="fileStoreId" column="file_store_id" jdbcType="INTEGER"/>
        <result property="role" column="role" jdbcType="INTEGER"/>
        <result property="userName" column="user_name" jdbcType="VARCHAR"/>
        <result property="email" column="email" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="registerTime" column="register_time" jdbcType="TIMESTAMP"/>
        <result property="imagePath" column="image_path" jdbcType="VARCHAR"/>
    </resultMap>

    <!--全部字段-->
    <sql id="allColumn"> user_id, open_id, file_store_id, user_name,email,password,register_time, image_path,role</sql>

    <!--添加语句的字段列表-->
    <sql id="insertColumn">
        <if test="openId != null and openId != ''">
            open_id,
        </if>
        <if test="fileStoreId != null">
            file_store_id,
        </if>
        <if test="userName != null and userName != ''">
            user_name,
        </if>
        <if test="email != null and email != ''">
            email,
        </if>
        <if test="password != null and password != ''">
            password,
        </if>
        <if test="registerTime != null">
            register_time,
        </if>
        <if test="imagePath != null and imagePath != ''">
            image_path,
        </if>
    </sql>

    <!--添加语句的值列表-->
    <sql id="insertValue">
        <if test="openId != null and openId != ''">
            #{openId},
        </if>
        <if test="fileStoreId != null">
            #{fileStoreId},
        </if>
        <if test="userName != null and userName != ''">
            #{userName},
        </if>
        <if test="email != null and email != ''">
            #{email},
        </if>
        <if test="password != null and password != ''">
            #{password},
        </if>
        <if test="registerTime != null">
            #{registerTime},
        </if>
        <if test="imagePath != null and imagePath != ''">
            #{imagePath},
        </if>
    </sql>

    <!--通用对User各个属性的值的非空判断-->
    <sql id="commonsValue">
        <if test="openId != null and openId != ''">
            open_id = #{openId},
        </if>
        <if test="fileStoreId != null">
            file_store_id = #{fileStoreId},
        </if>
        <if test="userName != null and userName != ''">
            user_name = #{userName},
        </if>
        <if test="email != null and email != ''">
            email = #{email},
        </if>
        <if test="password != null and password != ''">
            password = #{password},
        </if>
        <if test="registerTime != null">
            register_time = #{registerTime},
        </if>
        <if test="imagePath != null and imagePath != ''">
            image_path = #{imagePath},
        </if>
    </sql>

    <!--新增user:哪个字段不为空就添加哪列数据,返回自增主键-->
    <insert id="insert" keyProperty="userId" useGeneratedKeys="true">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <include refid="insertColumn"/>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <include refid="insertValue"/>
        </trim>
    </insert>

    <!--查询单个user:通过邮箱-->
    <select id="queryUserByEmail" resultMap="UserMap">
        select
        <include refid="allColumn"/>
        from user
        where email = #{email}
    </select>

    <!--查询单个user:通过邮箱和密码-->
    <select id="queryByEmailAndPwd" resultMap="UserMap">
        select
        <include refid="allColumn"/>
        from user
        <where>
            email = #{email} and password = #{password}
        </where>
    </select>

</mapper>
2.3 新建UserService.java(用户层接口)
package com.beyond.disk.service;

import com.beyond.disk.pojo.User;


/**
 * @author Beyond
 * @Description: 用户层接口
 * @date 2021/5/29 23:43
 */
public interface UserService {
    /**
    * @Description: 添加用户
    * @param user 实例对象
    * @return 布尔值
    * @author Beyond
    * @date 2021/5/29 23:44
    */
    boolean insert(User user);

    /**
     * @Description: 通过邮箱查询单条数据
     * @param email 邮箱
     * @return 实例对象
     * @author Beyond
     * @date 2021/5/29 22:56
     */
    User queryUserByEmail(String email);

    /**
    * @Description: 通过邮箱和密码查询单条数据
    * @param email 邮箱
    * @param password 密码
    * @return 实例对象
    * @author Beyond
    * @date 2021/5/29 23:48
    */
    User queryByEmailAndPwd(String email, String password);

}

2.4 新建UserServiceImpl.java(用户服务实现类)
package com.beyond.disk.service.impl;

import com.beyond.disk.pojo.User;
import com.beyond.disk.service.UserService;
import org.springframework.stereotype.Service;


/**
 * @author Beyond
 * @Description: 用户服务实现类
 * @date 2021/5/29 23:52
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    protected UserMapper userMapper;
	
    /**
     * @Description: 添加用户
     * @param user 实例对象
     * @return 布尔值
     * @author Beyond
     * @date 2021/5/29 23:44
     */
    @Override
    public boolean insert(User user) {
        return userMapper.insert(user) == 1;
    }

    /**
     * @Description: 通过邮箱查询单条数据
     * @param email 邮箱
     * @return 实例对象
     * @author Beyond
     * @date 2021/5/29 23:47
     */
    @Override
    public User queryUserByEmail(String email) {
        return userMapper.queryUserByEmail(email);
    }

    /**
     * @Description: 通过邮箱和密码查询单条数据
     * @param email 邮箱
     * @param password 密码
     * @return 实例对象
     * @author Beyond
     * @date 2021/5/29 23:48
     */
    @Override
    public User queryByEmailAndPwd(String email, String password) {
        return userMapper.queryByEmailAndPwd(email,password);
    }

}

2.5 新建LoginController.java(注册登录/登出控制器)
package com.beyond.disk.controller;

import com.beyond.disk.pojo.FileStore;
import com.beyond.disk.pojo.User;
import com.beyond.disk.utils.MailUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

/**
 * @author Beyond
 * @Description: 注册登录/登出控制器
 * @date 2021/5/30 00:13
 */
@Controller
public class LoginController extends BaseController {

    /**
    * @Description: 用于注册类流程,用户名、密码、邮箱等校验由前端完成
    * @param user 实例对象
    * @param code 验证码
    * @param map 视图
    * @return 跳转页面
    * @author Beyond
    * @date 2021/5/30 00:15
    */
    @PostMapping("/register")
    public String register(User user, String code, Map<String, Object> map) {
        String uCode = (String) session.getAttribute(user.getEmail()+"_code");
        if (!code.equals(uCode)) {
            map.put("errorMsg", "验证码错误");
            return "index";
        }
        user.setUserName(user.getUserName().trim());
        user.setImagePath("https://i.loli.net/2021/05/31/GJcmLonvkKyRFZD.png");
        user.setRegisterTime(new Date());
        if (userService.insert(user)) {
            FileStore store = FileStore.builder().userId(user.getUserId()).build();
            fileStoreService.addFileStore(store);
            user.setFileStoreId(store.getFileStoreId());
            userService.update(user);
        } else {
            map.put("errorMsg", "服务器发生错误,注册失败!");
            return "index";
        }
        session.removeAttribute(user.getEmail() + "_code");
        session.setAttribute("loginUser", user);
        return "main/index";
    }

    /**
    * @Description: 向注册邮箱发送验证码,并验证邮箱是否已使用
    * @param userName 用户名
    * @param email 邮箱
    * @param password 密码
    * @return 发送成功
    * @author Beyond
    * @date 2021/5/30 15:14
    */
    @ResponseBody
    @RequestMapping("/sendCode")
    public String sendCode(String userName, String email, String password) {
        User userByEmail = userService.queryUserByEmail(email);
        if (userByEmail != null) {
            return "exitEmail";
        }
        mailUtils = new MailUtils(mailSender);
        String code = mailUtils.sendCode(email, userName, password);
        session.setAttribute(email + "_code", code);
        return "success";
    }

    /**
    * @Description: 用户登录
    * @param user 实例对象
    * @param map 视图
    * @return 跳转页面
    * @author Beyond
    * @date 2021/6/2 08:10
    */
    @PostMapping("/login")
    public String login(User user, Map<String, Object> map) {
        User userByEmail = userService.queryUserByEmail(user.getEmail());
        if (userByEmail == null) {
            map.put("errorMsg", "用户不存在,登录失败!");
            return "index";
        }

        User userByEmailAndPwd = userService.queryByEmailAndPwd(user.getEmail(), user.getPassword());
        if (userByEmailAndPwd == null) {
            map.put("errorMsg", "密码错误!");
            return "index";
        }

        session.setAttribute("loginUser", userByEmailAndPwd);
        return "main/index";
    }

    /**
    * @Description: 退出登录
    * @return 返回登录页
    * @author Beyond
    * @date 2021/6/4 13:36
    */
    @GetMapping("/logout")
    public String logout() {
        session.invalidate();
        return "/beyond";
    }

}

2.6 新建邮件服务MailUtils.java
package com.beyond.disk.utils;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author Beyond
 * @Description: 邮件
 * @date 2021/5/30 14:30
 */
public class MailUtils {

    //从配置文件中注入发件人的姓名
    @Value("${spring.mail.username}")
    private String fromEmail;

    //邮件发送器
    private JavaMailSenderImpl mailSender;
    Logger logger = LogUtils.getInstance(MailUtils.class);

    public MailUtils(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    /**
    * @Description: 发送验证码
    * @param email 邮箱
    * @param userName 用户名
    * @param password 密码
    * @throws  MessagingException 消息异常
    * @return String
    * @author Beyond
    * @date 2021/5/30 14:32
    */
    public String sendCode(String email, String userName, String password) {
        int code = (int) ((Math.random()*9+1)*100000);
        logger.info("开始发送繁杂邮件...");
        logger.info("mailSender对象为:"+mailSender);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            messageHelper.setSubject("Beyond网盘-邮箱验证");
            messageHelper.setText("<h2 >Beyond网盘-简洁、优雅、免费</h2>" +
                    "<h3>用户注册-邮箱验证<h3/>" +
                    "您现在正在注册Beyond网盘账号<br>" +
                    "验证码: <span style='color : red'>"+code+"</span><br>" +
                    "用户名 :"+userName+
                    "<br>密码 :"+password+
                    "<hr>"+
                    "<h5 style='color : red'>如果并非本人操作,请忽略本邮件</h5>",true);
            messageHelper.setFrom(fromEmail);
            messageHelper.setTo(email);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        logger.info("mailSender对象为:"+mimeMessage);
        mailSender.send(mimeMessage);
        return String.valueOf(code);
    }
}

3. 本节完!
posted @ 2021-06-04 21:32  语海  阅读(542)  评论(0)    收藏  举报