栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Day 6】学习笔记Springboot仿牛客网论坛实现 -开发社区登录模块-注册(包括激活码发送校验)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

体会从产品的角度功能怎么实现

1 发送邮件功能 邮箱设置

邮箱默认没法从程序调用 启动客户端SMTP 服务 : 通过自己邮箱里的设置开启SMTP 服务

spring email 导入jar包

在mvn repository 网站搜索包 复制maven配置

Spring Boot Starter Mail

邮箱参数配置

在appalication.property 文件

spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=
spring.mail.password=
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

注意这里所填的密码不是邮箱密码是邮箱开启服务之后给的授权码

使用JavaMailSender发送邮件

写一个工具类封装他让他可以复用 新建包util包

注入JavaMailSender

逻辑: 通过服务器发邮件 发送人是固定的 是配置文件里的username

因此注入username

@Value
注解可以注入一些字段的普通属性,并且会自动进行类型转换

@Value("${}")
来注入配置文件里面的信息

@Value(“#{}”)

其实是SpEL表达式的值,可以表示常量的值,或者获取bean中的属性

@Value("#{1}")
	private int number; //获取数字 1
	
	@Value("#{'Spring Expression Language'}") //获取字符串常量
	private String str;
	
	@Value("#{dataSource.url}") //获取bean的属性
	private String jdbcUrl;

util包下的发送邮件工具类 代码

MimeMessage 通过Helper 来帮助发送

邮件的发送发即:(from) 自己 自己的邮箱已经通过@value 注入

邮件的接收方(to): 通过方法传入

package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

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

@Component
public class MailClient {
    private  static final Logger logger= LoggerFactory.getLogger(MailClient.class);
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private  String from;
    public void sendMail(String to, String subject, String content){
       try {
           MimeMessage message = mailSender.createMimeMessage();
           MimeMessageHelper helper = new MimeMessageHelper(message);
           helper.setFrom(from);
           helper.setTo(to);
           helper.setSubject(subject);
           helper.setText(content,true);
           mailSender.send(helper.getMimeMessage());
       } catch (MessagingException e){
           logger.error("发送邮件失败"+e.getMessage());
       }

    }
}
模板引擎

使用thymeleaf 发送一个html邮件 可以携带更为丰富的信息

做模板:

放在template 的mail目录下




    
    邮件实例


欢迎你,!

在这里1 因为用的是thymeleaf 所以要加上xmlns:th=“http://www.thymeleaf.com”>

2 欢迎你某某某 中间是变量用一个span 来书写

测试:

回忆:在普通的spring mvc 中如果想要使用模板引擎在controller中传入模板引擎的路径 dispachservlet 会帮我们自动调取

在这次我们要主动调取模板引擎

thymeleaf 模板引擎有一个核心的类 : TemplateEngine 这个类被spring 容器所管理 所以我们直接注入就可以使用。

package com.nowcoder.community;

import com.nowcoder.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail() {
        mailClient.sendMail("xliu1998@139.com", "TEST", "Welcome.");
    }

    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "judy");

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("xxxx@xxx.com", "HTML", content);
    }

}
二 : 开发注册功能

相对复杂的功能的拆解可以按照请求来

对于注册功能: 1 首页上注册的链接 -打开页面 (访问服务器就有一次请求)

2 在表单里填写数据 (访问服务器保存数据)

3 服务端验证账号是否存在,邮箱是否已注册

服务端发送激活邮件

激活注册账号 :点击邮件中的链接 访问服务端的激活服务

1 首页上的注册链接

分析: 点开链接所以没有什么业务 没有访问数据库 只需对视图层进行更改

对于视图层 由controller -调用模板 ,对浏览器进行响应

返回模板路径

@Controller
public class LoginController {
    @RequestMapping(path="/register",method = RequestMethod.GET)
    public  String getRegister(){
        return  "/site.register";
    }
}

页面的一些样式需要通过thymeleaf 进行管理




   
   
   
   
   
   
   牛客网-注册

其中css,js 改成thymeleaf 进行管理





首页的一些链接需要改变

在index。html文件中修改

此外: 由于头部都是一样的想要复用: th: fragment="header“


   


         

https://blog.csdn.net/Eurus1209/article/details/register.html




	
	
	
	
	
	
	牛客网-注册


注  册
该账号已存在!
密码长度不能小于8位!
两次输入的密码不一致!
该邮箱已注册!

2 提交注册数据

通过表单提交数据

导入包: commons lang

域名的设置

在注册的过程中要激活,激活有个链接 链接是网站 要把他设置成可配置,在配置文件中添加域名

#community
community.path.domain=http://localhost:8080

为了顺利注册需要生成一些通用工具类:

在util 包下

1 随机字符串

2加密方法

生成随机字符串如在验证码里,这个方法默认生成的字符串有_ 我们用tosrting().replaceall(“——”,“”); 去掉字符串 即 用空格代替下划线

2 加密 由于密码如果是简单密码存在不安全性 我们用md5 方法加密

另外:需要对输入进行一下非空判断

package com.nowcoder.community.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class CommunityUtil {
    //生成随机字符串
    public  static String generateUUID(){
        return UUID.randomUUID().toString().replaceAll("_", "");

    }
    //MD5 加密
    //特点 只能加密不能解密
    //简单加密所以需要加个盐
    public static String md5(String key){
        if (StringUtils.isBlank(key)){
            return  null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
}

开发功能;隶属于用户的service 所以写在service包下的userservice

1 注入bean

项目里需要发邮件,需要模版引擎;

    @Autowired
    private MailClient mailClientl
    @Autowired
    private TemplateEngine templateEngine;
    

不是bean 的注入

激活码需要注入域名 (community path)和项目名(context path)

@Value("${community.path.domain}")
    private String domain;//声明变量来接收
    @Value("${server.servlet.context-path}")//这个在application.properties文件里有
    private String contextPath;

返回给浏览器的可以是多种多样的信息 如: 邮箱已注册 手机号不存在

所以用map 来存储各种各样的值

初始化map 后对传进来的值(User)做判断

空值处理

如果传入的数据是空的 ;不是异常 返回一些错误信息

public Map register(User user) {
        Map map = new HashMap<>();

        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

验证是否已经存在

User u =userMapper.selectByName(user.getUsername());
if(u !=null) {
    map.put("usernameMsg","该账号已存在!");
return map;
}

//验证邮箱
u =userMapper.selectByEmail(user.getEmail());
if(u !=null) {
    map.put("emailMsg","该邮箱已被注册!");
return map;
}

对于新加入注册的用户 给每个用户的密码加盐

给用户设置等级,设置激活状态 和激活码 (激活码用随机生成字符串的工具)

最后新增的用户插入数据库

// 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

接受到表单后 要激活邮件发送

//激活邮件
Context context =newContext();
context.setVariable("email", user.getEmail());
// http://localhost:8080/community/activation/101/code
String url =domain+contextPath+"/activation/"+ user.getId() +"/"+ user.getActivationCode();
context.setVariable("url", url);
String content =templateEngine.process("/mail/activation", context);
mailClient.sendMail(user.getEmail(),"激活账号", content);

returnmap;

对于controller

//处理请求,因为是浏览器提交 所以是post请求
@RequestMapping(path="/register",method=RequestMethod.POST)
publicString Register (Model model, User user){
    Map map =userService.register(user);
//根据map的返回值进一步看怎么响应 ,
    //如果没有错误信息(map为空)注册成功--浏览器给提示 注册成功并且跳转到首页
    if(map==null||map.isEmpty()){
        model.addAttribute("msg","注册成功,我们已经向邮箱发送激活邮件");
        model.addAttribute("target","/index");

return"site/operate-result";}
else //如果有错误信息,返回注册页面 
{model.addAttribute("usernameMsg", map.get("usernameMsg"));
        model.addAttribute("passwordMsg", map.get("passwordMsg"));
        model.addAttribute("emailMsg", map.get("emailMsg"));
return"/site/register";}

    }
激活

目的:改变用户的激活状态

在service 层加入业务方法

处理激活时: 成功,重复激活 需要提示,激活码不对 失败

先定义一个常量接口保存一些状态可以复用

packagecom.nowcoder.community.util;

public interface CommunityConstant {

intACTIVATION_SUCCESS=0;
intACTIVATION_REPEAT=1;
intACTIVATION_FAILURE=2;
}

1.接口当中的常量,可以省略public static final,注意,不写也照样是这样。

2.接口当中的常量,必须进行赋值,不能不赋值。

3.接口中常量的名称,使用完全大写字母,用下划线进行分割。(推荐命名规则)

Userservice 处理的时候要用到这个常量接口的数据 所以 userservice 实现这个接口

方法返回激活的状态:

传入的参数user id 和激活码

查到用户的id 然后判断激活码对不对

public int activation (int userId, String code){
        User user= userMapper.selectById(userId);
    if(user.getStatus()==1){
        return ACTIVATION_REPEAT;
        

    }else if (user.getActivationCode().equals(code)){
        userMapper.updateStatus(userId,1);
        return ACTIVATION_SUCCESS;
    }else return  ACTIVATION_FAILURE;
}

controller 请求处理 :在log-in controller 层加入activation 方法

请求是个页面 页面的路径之前定义好了

//激活路径http://localhost8080:community/activation/101(用户id)/code(激活码)

请求是get : 因为激活的时候邮件不是一个表单,只是利用路径携带了两个条件最终期待获取一个结果 所以== 查询

//激活路径http://localhost8080:community/activation/101(用户id)/code(激活码)
    @RequestMapping(path="/activation/(userId)/(code)",method = RequestMethod.GET )
    public String activation (Model model, @PathVariable("userId") int userId, @PathVariable("code") String code){
        //@PathVAriable 获取路径中的值
        int result= userService.activation(userId,code);
        //判断result 属于什么 - 利用接口
        if (result==ACTIVATION_SUCCESS){
            //成功跳到首页
        model.addAttribute("msg","激活成功");
        model.addAttribute("target","/login");
        
        }
        else if (result==ACTIVATION_REPEAT){
            model.addAttribute("msg","操作无效,该账号已经激活");
            model.addAttribute("target","/index");

        }
        else { model.addAttribute("msg","激活失败,您提供的激活码不正确");
            model.addAttribute("target","/index");

        }
        return  "/site/operate-result";
    }

处理登录页面

@RequestMapping(path="/login",method = RequestMethod.GET)
publicString getLoginPage(){
return"/site/login";

}

Login controller 完整代码

并且在login。html 添加相应的配置
Login controller 完整代码

并且在login。html 添加相应的配置

package com.nowcoder.community.Controller;

import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {
    @Autowired
    private UserService userService;
    @RequestMapping(path="/register",method = RequestMethod.GET)
    public  String getRegister(){
        return  "/site/register";
    }
    //处理请求,因为是浏览器提交 所以是post 请求
    @RequestMapping(path="/register",method=RequestMethod.POST)
    public String Register (Model model, User user){
        Map map =userService.register(user);
        //根据map 的返回值进一步看怎么响应 ,
        //如果没有错误信息(map 为空)注册成功--浏览器给提示 注册成功并且跳转到首页
        if (map==null||map.isEmpty()){
            model.addAttribute("msg","注册成功,我们已经向邮箱发送激活邮件");
            model.addAttribute("target","/index");

            return  "site/operate-result";}
        else
        {model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return  "/site/register";}

        }
    //激活路径http://localhost8080:community/activation/101(用户id)/code(激活码)
    @RequestMapping(path="/activation/{userId}/{code}",method = RequestMethod.GET )
    public String activation (Model model, @PathVariable("userId") int userId, @PathVariable("code") String code){
        //@PathVAriable 获取路径中的值
        int result= userService.activation(userId,code);
        //判断result 属于什么 - 利用接口
        if (result==ACTIVATION_SUCCESS){
            //成功跳到首页
        model.addAttribute("msg","激活成功");
        model.addAttribute("target","/login");

        }
        else if (result==ACTIVATION_REPEAT){
            model.addAttribute("msg","操作无效,该账号已经激活");
            model.addAttribute("target","/index");

        }
        else { model.addAttribute("msg","激活失败,您提供的激活码不正确");
            model.addAttribute("target","/index");

        }
        return  "/site/operate-result";
    }
    @RequestMapping(path="/login",method = RequestMethod.GET)
    public String getLoginPage(){
        return  "/site/login";

    }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/941303.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号