BBS论坛项目相关-2:邮件激活和注册模块

BBS论坛项目相关-2:邮件激活和注册模块

实现功能:

访问注册页面;
提交注册数据:通过表单提交数据;-服务端验证账号是否已存在,邮箱是否已注册,服务端发送激活邮件
激活注册账号:点击邮件中的连接,访问服务端的激活服务。

工具类:

生成随机字符串

    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

MD5加密,加盐MD5,添上随机字符串进行加密

    // hello -> abc123def456
    // hello + 3e4a8 -> abc123def456abc
    public static String md5(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
登陆验证:

service层

public Map<String, Object> register(User user) {
        Map<String, Object> 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 = new Context();
        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);

        return map;
    }

发送邮件时,对url的拼接主要用@value注解引入.properties中的属性值,作为成员变量,便于之后变更时统一变更路径

@Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

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

@Value注解
@value("#{}")SpEL表达式,用于获取bean的属性值,或调用某个bean的某个方法,也可加数字,为变量命值。@Value(#{“”}) 获取其他bean的属性,或者调用其他bean的方法时,只要该bean (Beab_A)能够访问到被调用的bean(Beab_B),即要么Beab_A 和Beab_B在同一个容器中,或者Beab_B所在容器是Beab_A所在容器的父容器。如dataSource这个bean一般是在springContext.xml文件中申明的,而loginController这个bean一般是在springMvc.xml文件中申明的,虽然这两个bean loginController和dataSource不在一个容器,但是loginController所在容器继承了dataSource所在的容器,所以在loginController这个bean中通过@Value(“#{dataSource.url}”)能够获取到dataSource的url属性。
@value("${}")用于获取.properties文件的值

templateEngine.processthemleaf模板渲染页面,并通过mailClient发送邮件,这样邮件里就是以activation.html为模板的内容,带有拼接好的链接。

controller层:

@RequestMapping(path = "/register", method = RequestMethod.POST)
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        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";
        }
        /*
        前端读取model中的信息为用户提示,th:text="${msg}"
        注意前端要传递的值需要有name属性,不然无法传递,且name值要与传送到后端的对象的属性值一一对应
        */
    }

前端代码的复用

用户激活

定义几个激活状态的常量

public interface CommunityConstant {
    /**
     * 激活成功
     */
    int ACTIVATION_SUCCESS = 0;
    /**
     * 重复激活
     */
    int ACTIVATION_REPEAT = 1;
    /**
     * 激活失败
     */
    int ACTIVATION_FAILURE = 2;
}

service层:
查看是否已经激活状态,查看传过来的code是否与注册时的用户code一致,返回相应常量值作为状态。

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);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

controller层:
点击邮箱里的链接后会进入该控制层,链接中已经将用户id和code传过来了,接收并传到service层,service层处理后返回状态值,判断状态值,向model中放置msg

// http://localhost:8080/community/activation/101/code
    @RequestMapping(path = "/activation/{userId}/{code}", method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int result = userService.activation(userId, code);
        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";
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值