chapter2 登录模块

1、发送邮件

(1)将包导入到pom.xml文件中

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

(2)在application中对邮箱相关参数进行配置

#MailPeoperties
#spring.mail.host=smtp.163.com
spring.mail.host=smtp.qq.com
#spring.mail.port=465
spring.mail.username=XXXXXX@qq.com
spring.mail.password=XXXXXX

(3)新建发送邮件工具  util/MailClient.java

import org.slf4j.Logger;
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 org.slf4j.LoggerFactory;

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("1194380923@qq.com");
//            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            mailSender.send(helper.getMimeMessage());
        }catch (MessagingException e){
            logger.error("发送有件事失败:" + e.getMessage());
        }


    }
}

2、注册功能

(1)controller/LoginController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

    @RequestMapping(path = "/register",method = RequestMethod.GET) //声明在网页中的访问路径
    public String getRegisterPage(){
        return "/site/register"; //返回html模板路径
    }
}

(2)设置resource/template/sit/register.html

(3)复用html代码片段,

在需要定义为模板的标签上定义:

th:fragment="header",其中header是自定义命名,类似于变量名
<header class="bg-dark sticky-top" th:fragment="header">

然后再需要对模板进行复用的标签上定义:

th:replace="index::header",其中header是上面的header
<header class="bg-dark sticky-top" th:replace="index::header">

(3)编写用户验证工具 util/CommunityUtil.java

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 generatrUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    //MD5加密
    public static String md5(String key){
        if(StringUtils.isBlank(key)) return null;
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
}

(4)完善 service/UserService.java

package com.nowcoder.community.service;

import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserService {
    @Autowired //注入bean
    private UserMapper userMapper;

    public User findUserById(int id){
        return userMapper.SelectById(id);
    }

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine; //模板引擎

    @Value("${community.path.domain}") //注入值
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

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

        //null
        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;
        }
        //验证邮箱
        User e = userMapper.SelectByEmail(user.getEmail());
        if(e != null){
            map.put("emailmsg","该邮箱已存在");
            return map;
        }


        //开始注册用户
        user.setSalt(CommunityUtil.generatrUUID().substring(0,5)); //
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generatrUUID());//设置激活码
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));//生成随机图片
        user.setCreateTime(new Date());
        userMapper.insertUser(user); //向数据库中插入数据


        //激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        String url = domain + contextPath+"/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("uel",url);
        String content = templateEngine.process("/mail/activation",context); //拼接前端页面
        mailClient.sendMail(user.getEmail(),"激活账号",content);



        return map;
    }


}

(5)激活注册账号

3、会话管理

(1)cookies:

cookies是无连接状态的http,可以记录浏览器对服务器的访问

        1)服务器第一次想浏览器发送数据的时候,携带一个cookies值,此时浏览器将这一小块数据保存到本地

        2)下次浏览器想服务器再次发送请求的时候,携带这块数据表示,这是“老客户”

缺点:数据存储在浏览器上,1)占用浏览器内存,2)数据安全性无法保障,3)数据传输效率低

(2)session

产生的效果和cookies一样,都是使服务器记住浏览器

数据存放在服务端,内存压力大,但是数据安全

(3)分布式

分布式部署的问题:某浏览器与服务器一交互,在服务器一创建了一个session,并得到了sessionid,然后,该浏览器与服务器三交互,把sessionid传过去,却没得到值,只好在服务器三再创建一个session。
解决方案:

1、粘性session。同一个ip,永远分到同一个服务器处理。
缺点:难以保证负载均衡。
2、同步session。某服务器创建一个session后,把session同步到其他的服务器。
缺点:1、同步会对服务器性能产生影响。2、服务器与服务器间产生耦合,对部署有影响。
3、共享session。专门搞一台服务器来存session,其他服务器都找这台服务器来获取session。
缺点:1、这台专门存session的服务器挂了,其他的处理业务的服务器就都没办法工作了。2、分布式部署是为了解决性能瓶颈,现在又搞出一个单体的session服务器,那么这个单体的session服务器就成为了瓶颈。3、如果搞一个session服务器集群的话,那和同步session这个解决方案差不多,也要处理同步问题。

最终解决方案:能存cookie里就存cookie里,敏感数据不能存到cookie里,就存到Redis里。
————————————————

(这段抄的,懒得写)
版权声明:本文为CSDN博主「夜中听雪」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wpw2000/article/details/116462109

(4)生成验证码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值