二 仿牛客网论坛-邮件发送,注册,验证码

本文展示了如何使用Spring Boot实现邮件发送功能,包括普通文本邮件和HTML邮件,并结合Thymeleaf模板引擎生成激活链接。此外,还介绍了用户注册流程,包括随机字符串生成、MD5加密、数据验证、用户信息存储以及激活邮件的发送。同时,配置了Kaptcha生成验证码并存储在服务器端session中,确保注册过程的安全性。
摘要由CSDN通过智能技术生成

一 邮件发送
在util包下建立MailClient类处理邮件发送
(发送人,收件人,主题,发送内容)

@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) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);
        mailSender.send(helper.getMimeMessage());

    }
}

发送测试

// 测试发送普通邮件
    @Test
    public void testTextMail() throws MessagingException {
        mailClient.sendMail("873969432@qq.com","TEST"," this is wangsuhang speaking");
    }

    // 测试发送HTML文件,这里是要根据用户名设置对应的HTML
    @Test
    public void testHtmlMail() throws MessagingException {
        // 导入的是 :org.thymeleaf.context.Context;
        Context context = new Context();
        // 填充的是 HTML 中的:变量
        context.setVariable("username","json");

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

        mailClient.sendMail("873969432@qq.com","html",content);
    }

二 注册功能
CommunityUtil生成随机字符串 和 MD5加密

 //生成随机字符串
    public static String generateUUID(){
        return UUID.randomUUID().toString().replace("-","");


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

    }

提交表单数据(username,password,email)
调用服务层register方法处理
判断(账户,密码,邮箱是否为空)
–>生成随机盐–>密码+随机盐进行MD5加密–>设置加密后的密码,账户类型,状态(是否激活),激活code,创建时间,头像
–>插入数据库
最后发送激活邮件(邮件链接activation/userId/code)

   public Map<String, Object> register(User user) throws MessagingException {
        Map<String , Object> map=new HashMap<>();
        if(user == null ){
            throw new IllegalArgumentException("用户不存在");
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            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.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword())+user.getSalt());
        user.setType(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setCreateTime(new Date());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));

        userMapper.insertUser(user);
        //激活邮件
        Context context=new Context();
        context.setVariable("email",user.getEmail());
        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);
        return  map;

    }

控制层根据邮件链接(activation/userId/code)
激活注册用户(修改用户status)

 @RequestMapping(value = "/activation/{userId}/{code}",method = RequestMethod.GET)
    public String activation(@PathVariable("userId") int userId,@PathVariable("code") String code,Model model ){
        int activation = userService.activation(userId, code);
        if(activation == ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target","/login");
        }else if (activation == ACTIVATION_REPEAT) {
            model.addAttribute("msg","无效操作,该账号已经激活了!");
            model.addAttribute("target","/index");
        } else {
            model.addAttribute("msg","激活失败,您提供的激活码不正确!");
            model.addAttribute("target","/index");
        }

        return "/site/operate-result";


    }

三 验证码


@Configuration
public class KaptchaConfig {

    @Bean
    public Producer kaptchaProducer() {


        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width","100");
        properties.setProperty("kaptcha.image.height","40");
        properties.setProperty("kaptcha.textproducer.font.size","32");
        properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
        properties.setProperty("kaptcha.textproducer.char.string","123456789abcedefghijklmnopqrstuvwxyz");
        properties.setProperty("kaptcha.textproducer.char.length","4");
        properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");


        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }


}

用session存入验证码到服务器端

 @RequestMapping(value = "/kaptcha",method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //将验证码存入session
        session.setAttribute("kaptcha",text);
        //将图片输出给浏览器
        response.setContentType("/imgae/png");
        try {
           ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

四 前端页面
index主页修改

<a class="nav-link" th:href="@{/register}">注册</a>

跳转到注册页面

@RequestMapping(value = "/register",method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

register.html修改

<h3 class="text-center text-info border-bottom pb-3">&nbsp;&nbsp;</h3>
				<form class="mt-5" method="post" th:action="@{/register}">

提交表单响应服务器register方法

<input type="text"
								   th:class="|form-control ${usernameMsg!=null?'is-invalid':''}|"
								   th:value="${user!=null?user.username:''}"
								   id="username" name="username" placeholder="请输入您的账号!" required>
							<div class="invalid-feedback" th:text="${usernameMsg}">
<input type="password"
								   th:class="|form-control ${passwordMsg!=null?'is-invalid':''}|"
								   th:value="${user!=null?user.password:''}"
								   id="password" name="password" placeholder="请输入您的密码!" required>
							<div class="invalid-feedback" th:text="${passwordMsg}">
								密码长度不能小于8!
							</div>	
<div class="col-sm-10">
							<input type="password" class="form-control"
								   th:value="${user!=null?user.password:''}"
								   id="confirm-password" placeholder="请再次输入密码!" required>
							<div class="invalid-feedback">
								两次输入的密码不一致!
							</div>
	<input type="email"
								   th:class="|form-control ${emailMsg!=null?'is-invalid':''}|"
								   th:value="${user!=null?user.email:''}"
								   id="email" name="email" placeholder="请输入您的邮箱!" required>
							<div class="invalid-feedback" th:text="${emailMsg}">
								该邮箱已注册!
							</div>
仿牛客UI(张俊峰) 1.图标来自牛客app 2.大致实现UI效果 3.实现抽提 底部:RelativeLayout(学习、社区、消息、我的牛客) + 中间 自定义ViewPager(禁止滑动) 一、学习界面: (1) 标题模块:牛客 (2) 图片滑动模块:ViewPager+Pager (3) 签到模块:显示(已打卡、今日刷题、今日学习、共打卡) (4) 学习模块:Linearlayout(可用GridView)(专题练习、公司套题、错题练习、课程学习、大题查看、期末备考) ? 点击中任何一个LAYOUT,会显示一个由ExpandableList实现一个列表 ? 点击ExpandabList子标签中的练习字样,会自动跳转到另一个Activity,进行专项练习。 ? 可以进行考试,有倒计时,要求达到牛客网的效果,并能出考试结果。 (5) 参与模块:(文字(我参与的课程)+添加按钮) ? 点击添加按钮跳转到另一页面。由 ListView实现 、 社区界面: 1. 标题模块:显示文字(最新),点击最新会弹出一个上下文菜单(最新、最热、精华)。 2. 滑动标题模块:ViewPager+PagerSlidingTabStrip 3. 内容模块:使用ListView显示用户内容。 三、 消息界面: 1、 菜单模块:(朋友私信、系统通知)使用ViewPager实现(可用Tabhost) 2、 朋友私信页面:显示一个私信图片 3、 系统通知页面:(由ListView实现)由于比较固定本人使用RelativeLayout实现 四、 我的牛客界面: 1. 头像显示模块:头像+用户名+用户信息 2. 内容显示模块 更多效果请试用,感谢支持!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值