IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 项目实训(3)-邮件 -> 正文阅读

[Java知识库]项目实训(3)-邮件


前言

经过商量,修改注册逻辑,用户首先填写用户名和邮箱字段,后端向用户邮箱发送验证码,用户再填写验证码和邮箱进行激活账号。

邮箱配置

在pom文件中,引入启动器。

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

修改yaml文件。

spring:
  mail:
    # 发送邮件服务器
    host: smtp.163.com
    # 发送邮件的邮箱地址
    username: 邮箱地址
    # 客户端授权码
    password: 密码
    # 465或者994
    properties.mail.smtp.port: 465
    # 下面配置有兴趣可以自行查阅
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

service

修改后的UserService.java

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private MailService mailService;

    @Autowired
    private UUIDUtil uuidUtil;

    @Autowired
    private DigitUtil digitUtil;

    @Autowired
    private Md5Util md5Util;

    @Transactional(rollbackFor = RuntimeException.class)
    public User loadUserByUsername(String username) {
        User user = userMapper.findUserByUsername(username);
        if (user == null) {
            return user;
        }
        Long uid = user.getId();
        List<Role> authorities = new ArrayList<>();
        List<UserRole> userRoles = userRoleMapper.findUserRolesByUid(uid);
        for (UserRole userRole : userRoles) {
            authorities.add(roleMapper.findRoleById(userRole.getRid()));
        }
        user.setAuthorities(authorities);
        return user;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public User loadUserByEmail(String email) {
        User user = userMapper.findUserByEmail(email);
        if (user == null) {
            return user;
        }
        Long uid = user.getId();
        List<Role> authorities = new ArrayList<>();
        List<UserRole> userRoles = userRoleMapper.findUserRolesByUid(uid);
        for (UserRole userRole : userRoles) {
            authorities.add(roleMapper.findRoleById(userRole.getRid()));
        }
        user.setAuthorities(authorities);
        return user;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void code(String username, String password, String email) {
        if (username.contains("@")) {
            throw new IllegalUsernameException("用户名不合法");
        }
        if ((userMapper.findUserByUsername(username)) != null) {
            throw new UserExistException("用户名已经存在");
        }
        if ((userMapper.findUserByEmail(email)) != null) {
            throw new UserExistException("邮箱已经存在");
        }
        String code = Integer.toString(digitUtil.code(6));
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(md5Util.encrypt(password));
        user.setProfile("default.png");
        user.setCode(code);
        userMapper.insertUser(user);
        userRoleMapper.insertNormalUser(user.getId());
        String subject = "山大云会议";
        String context = "<p>您的验证码为: "+code+"。</p>";
        try {
            mailService.sendHtmlMail(user.getEmail(), subject, context);
        } catch (MessagingException e) {
            throw new RuntimeException("发送邮件时出现异常");
        }
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public Long register(String username, String password, String email, String code) {
        User user = userMapper.findUserByCode(code);
        if (user == null) {
            throw new CodeNotFoundException("不存在的验证码");
        }
        if (!Objects.equals(username, user.getUsername())) {
            throw new UsernameNotFoundException("不存在的用户名");
        }
        if (!Objects.equals(email, user.getEmail())) {
            throw new EmailNotFoundException("不存在的邮箱");
        }
        user.setPassword(md5Util.encrypt(password));
        user.setStatus(1);
        user.setCode("");
        userMapper.updateUser(user);
        return user.getId();
    }

}

添加的MailService.java

@Service
public class MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendHtmlMail(String to, String subject, String context)
            throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setSubject(subject);
        helper.setTo(to);
        helper.setText(context, true);
        javaMailSender.send(message);
    }

}

controller

修改后的UserController.java

@Controller
@CrossOrigin(origins = {"*"})
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private Md5Util md5Util;

    private final static String EMAIL_PATTERN = "@mail.sdu.edu.cn";

    @ResponseBody
    @PostMapping("/login")
    public ResponseData login(@RequestParam("text") String text,
                              @RequestParam("password") String password) {
        ResponseData responseData;
        User user;
        if (checkValidEmail(text)) {
            user = userService.loadUserByEmail(text);
        } else {
            user = userService.loadUserByUsername(text);
        }
        if (user != null) {
            if (md5Util.verify(password, user.getPassword())) {
                responseData = new ResponseData(200, "ok");
                responseData.getData().put("token", jwtTokenUtil.generateToken(user));
            } else {
                responseData = new ResponseData(400, "密码错误");
            }
        } else {
            responseData = new ResponseData(400, "用户名或者邮箱不存在");
        }
        return responseData;
    }

    @ResponseBody
    @PostMapping("/code")
    public ResponseData code(@RequestParam("username") String username,
                             @RequestParam("email") String email) {
        ResponseData responseData;
        if (isStringEmpty(username) || isStringEmpty(email)) {
            responseData = new ResponseData(400, "不能为空");
            return responseData;
        }
        String password = "111111";
        if (!checkValidLength(username, password, email)) {
            responseData = new ResponseData(400, "长度问题");
            return responseData;
        }
        if (!checkValidEmail(email)) {
            responseData = new ResponseData(400, "不支持的邮件格式");
            return responseData;
        }
        try {
            userService.code(username, password, email);
            responseData = new ResponseData();
            responseData.setCode(200);
            responseData.setMessage("ok");
            return responseData;
        } catch (IllegalUsernameException exception) {
            responseData = new ResponseData(400, exception.getMsg());
            return responseData;
        } catch (UserExistException exception) {
            responseData = new ResponseData(400, exception.getMsg());
            return responseData;
        } catch (RuntimeException exception) {
            responseData = new ResponseData(400, exception.getMessage());
            return responseData;
        }
    }

    @ResponseBody
    @PostMapping("/register")
    public ResponseData register(@RequestParam("username") String username,
                                 @RequestParam("password") String password,
                                 @RequestParam("email") String email,
                                 @RequestParam("code") String code) {
        ResponseData responseData;
        if (isStringEmpty(username) || isStringEmpty(email)) {
            responseData = new ResponseData(400, "不能为空");
            return responseData;
        }
        if (!checkValidLength(username, password, email)) {
            responseData = new ResponseData(400, "长度问题");
            return responseData;
        }
        if (!checkValidEmail(email)) {
            responseData = new ResponseData(400, "不支持的邮件格式");
            return responseData;
        }
        try {
            Long uid = userService.register(username, password, email, code);
            responseData = new ResponseData(200, "ok");
            responseData.getData().put("uid", uid);
            return responseData;
        } catch (CodeNotFoundException | UsernameNotFoundException | EmailNotFoundException exception) {
            responseData = new ResponseData(400, exception.getMessage());
            return responseData;
        }
    }

    private boolean isStringEmpty(String string) {
        return string == null || "".equals(string);
    }

    private boolean checkValidLength(String username, String password, String email) {
        return username.length() <= 32 && password.length() <= 32 && email.length() <= 64;
    }

    private boolean checkValidEmail(String email) {
        return email.endsWith(EMAIL_PATTERN);
    }

}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-04-14 23:36:51  更:2022-04-14 23:40:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 4:21:59-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码