Bootstrap

springboot邮箱注册

1.准备工作

操作之前准备两个邮箱

我准备了网易邮箱和QQ邮箱,网易邮箱用来发送验证码,QQ邮箱用来做注册(希望大家和我一样,不然可能会出错                  )

发送验证码的邮箱需要开启一些设置,否则不能发送验证码

网易免费邮箱 - 你的专业电子邮局

网易邮箱官网,没有的注册一个,有的直接输入账号密码登录,

1.登录后点击设置

2.继续操作

3.保证两个服务开启:

IMAP/SMTP服务:
POP3/SMTP服务:

 4.生成授权码(授权码要保存起来,只能查看一次,)

 将生成的授权码放入properties配置文件 (稍后会用)

server.port=8081
restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
spring.mvc.static-path-pattern=/static/**
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true
mybatis.type-aliases-package=com.dss.springboot.entity
mybatis.mapper-locations=classpath:mapper/**/*.xml
spring.mail.default-encoding=utf-8
spring.mail.host=smtp.163.com
[email protected]
spring.mail.password=
spring.mail.protocol=smtp
spring.mail.port=25







       根据配置文件修改成自己的数据库和密码

发送消息的账号添加到

[email protected]

 其他设计默认即可

4.创建数据库

 

 5.新建数据库

 

6.用户表语句:

user表 数据库建表语句:

create table user
(
    uid      int auto_increment
        primary key,
    username varchar(255) not null,
    password varchar(255) not null,
    nickname varchar(255) null,
    email    varchar(255) not null,
    state    int          not null,
    code     varchar(255) null
);

在控制台执行

 

2.开始搭建:

 

选择有项目 sdk 8+java8 没有的随便选等创建 项目完成在修改

 将文件复制到properties

1.properties
server.port=8081
restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
spring.mvc.static-path-pattern=/static/**
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20

spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true
mybatis.type-aliases-package=com.dss.springboot.entity
mybatis.mapper-locations=classpath:mapper/**/*.xml
spring.mail.default-encoding=utf-8
spring.mail.host=smtp.163.com
[email protected]
spring.mail.password=你邮箱生成的授权码 
spring.mail.protocol=smtp
spring.mail.port=25


 
2. 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dss</groupId>
    <artifactId>springboot--javaMail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>emailtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 引入 thymeleaf 模板依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- 引入数据源依赖,这里使用alibaba的druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!-- mysql的连接依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
        <!--mybatis相关依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- 支持发送邮件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
3.连接数据库

 

 

4.修改文件设置,

5. 启动项目(检验配置是否成功)

 

6. 配置注册页面
 

 

 resource目录下templates 下 新建 thymeleaf 文件夹 新建页面

register.html
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>

<form action="/user/register" method="post">
	用户名:<input type="text" name="username" id="username"/><br/>
	密码:<input type="password" name="password" id="password"/><br/>
	确认密码:<input type="password" name="password1" id="password1"/><br/>
	昵称:<input type="text" name="nickname" id="nickname"/><br/>
	邮箱:<input type="text" name="email" id="email"/><br/>
	<input type="submit" value="注册"/>
</form>

</body>
</html>
result.html

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>

<h1 th:text="${message}"></h1>

</body>
</html>
7. 用mybatisx

生成 实体类 mapper 层 service 层 imp层   mapper.xml

 

 

 

 

 

 

 

 

 

 整理后项目结够如下

 

 

 

 8.添加工具类
package com.dss.javaMail.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * 发送邮件的工具类
 * @author duan ss
 *
 */
@Component
public class MailUtil {

	@Autowired
	private JavaMailSender javaMailSender;

	/**
	 * 发送邮件
	 * @param toUser	收件人
	 * @param code		激活码
	 * @return
	 */
	public String send(String toUser, String code) {

		// 建立邮件消息
		SimpleMailMessage mainMessage = new SimpleMailMessage();

		// 发送者
		mainMessage.setFrom("[email protected]");

		// 接收者
		mainMessage.setTo(toUser);

		// 发送的标题
		mainMessage.setSubject("注册激活邮件");

		// 发送的内容
		mainMessage.setText("<h1>来自xxx网站的注册激活邮件,激活请点击以下链接:http://localhost:8081/user/regActive?code="+code+"");

		javaMailSender.send(mainMessage);

		return "success";
	}

}
 9.编写各层代码
 mapper层

 

package com.example.emailtest.mapper;

import com.example.emailtest.domain.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
* @author l
* @description 针对表【user】的数据库操作Mapper
* @createDate 2024-02-23 12:49:21
* @Entity com.example.emailtest.domain.User
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
    void registerUser(User user);

    User getUserByCode(User user);

    void updateState(User user);

    User getUserByUsernameAndPassword(String username, String password);
}




       

service层
package com.example.emailtest.service;

import com.example.emailtest.domain.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
* @author l
* @description 针对表【user】的数据库操作Service
* @createDate 2024-02-23 12:49:21
*/
public interface UserService extends IService<User> {

    void registerUser(User user);

    User getUserByCode(User user);

    void updateState(User user);


    User getUserByUsernameAndPassword(String username, String password);
}
serviceimpl层
package com.example.emailtest.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.emailtest.domain.User;
import com.example.emailtest.service.UserService;
import com.example.emailtest.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author l
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-02-23 12:49:21
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void registerUser(User user) {
        userMapper.registerUser(user);
    }

    @Override
    public User getUserByCode(User user) {
        return userMapper.getUserByCode(user);
    }

    @Override
    public void updateState(User user) {
        userMapper.updateState(user);
    }

    @Override
    public User getUserByUsernameAndPassword(String username, String password) {
        return userMapper.getUserByUsernameAndPassword(username, password);
    }
}




mapper.xml层
<?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.example.emailtest.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.example.emailtest.domain.User">
            <id property="uid" column="uid" jdbcType="INTEGER"/>
            <result property="username" column="username" jdbcType="VARCHAR"/>
            <result property="password" column="password" jdbcType="VARCHAR"/>
            <result property="nickname" column="nickname" jdbcType="VARCHAR"/>
            <result property="email" column="email" jdbcType="VARCHAR"/>
            <result property="state" column="state" jdbcType="INTEGER"/>
            <result property="code" column="code" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="Base_Column_List">
        uid,username,password,
        nickname,email,state,
        code
    </sql>
    <insert id="registerUser" parameterType="com.example.emailtest.domain.User">
        insert into user values(#{ uid}, #{username}, #{password}, #{nickname}, #{email}, #{state}, #{code})
    </insert>
    <update id="updateState">
        update user set state = 1 where uid = #{uid} and code = #{code}
    </update>
    <select id="getUserByCode" resultType="com.example.emailtest.domain.User">
        select * from user where code = #{code}
    </select>
    <select id="getUserByUsernameAndPassword" resultType="com.example.emailtest.domain.User">
select * from user where username = #{username} and password = #{password}
    </select>
</mapper>

controller层
package com.example.emailtest.controller;

import com.example.emailtest.domain.User;
import com.example.emailtest.mapper.UserMapper;
import com.example.emailtest.service.UserService;
import com.example.emailtest.utils.MailUtil;
import com.example.emailtest.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;




import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Resource
	UserMapper userMapper;
	@Autowired
	private UserService userService;

	@Autowired
	private MailUtil mailUtil;

	@RequestMapping(value = "/goReg")
	public String getUser() {

		return "thymeleaf/register";

	}

	@RequestMapping(value = "/register")
	@ResponseBody
	public String register(User user) {

		user.setState(0);		//	0表示未激活/1表示激活
		user.setCode(UuidUtil.get32UUID());

		String result = mailUtil.send(user.getEmail(), user.getCode());

		System.out.println("发送邮件结果: " + result);

		System.out.println(user);

		userService.registerUser(user);

		return "success";
	}

	@RequestMapping(value = "/regActive")
	public String regActive(@RequestParam("code") String code,ModelMap map) {

		User user = new User();
		user.setCode(code);

		user = userService.getUserByCode(user);

		if(user != null) {

			if(user.getState() == 1) {

				map.addAttribute("message", "你已经激活过了...");

			}else {
				userService.updateState(user);
				map.addAttribute("message", "激活成功...");
			}

		}else {

			map.addAttribute("message", "激活失败...");
		}


		return "thymeleaf/result";
	}




}

启动类加mappscan注解!!!!!!!!!!!!!!!
package com.example.emailtest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.emailtest.mapper")
@SpringBootApplication
public class EmailtestApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmailtestApplication.class, args);
    }

}

3.启动项目:

注册接口地址

http://localhost:8081/user/goReg

邮件会收到消息

输入激活码

 数据库如下:

激活的账号state为1

 

4.todo 正在准备邮箱登录

;