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

数据与信息资源共享平台(八)

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

数据与信息资源共享平台(八)

邮箱注册/密码找回/认证
  • 后端
    • UserController.java
    • UserMapper.xml
    • StringUtil.java
    • UserService.java-接口
    • UserServiceImpl.java-接口实现逻辑
  • 前端
    • 注册
    • 找回密码

后端 UserController.java

邮箱注册

 @RequestMapping("/register.do")
    public OutResponse registerdo( User user) {

        OutResponse outResponse = new OutResponse<>();
        try {
            userService.register(user);
            outResponse.setCode(CodeEnum.SUCCESS);

        } catch (BussinessException e) {
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error("用户注册失败,用户名:{}邮箱:{}", user.getUserName(), user.getEmail());
        } catch (Exception e) {
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error("用户注册失败,用户名:{}邮箱:{}", user.getUserName(), user.getEmail());
        }
        return outResponse;
    }
 

邮箱账户激活

 @RequestMapping("/activate")
    public ModelAndView activate(String userName, String activationCode) {

        OutResponse outResponse = new OutResponse<>();
        ModelAndView view = new ModelAndView("/page/active");
        try {
            userService.updateUserActivate(userName, activationCode);
            outResponse.setCode(CodeEnum.SUCCESS);
            outResponse.setMsg("尊敬的【"+userName+"】用户,恭喜您账户激活成功");
        } catch (BussinessException e) {
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error("用户激活失败,用户名:{}", userName);
        } catch (Exception e) {
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error("用户激活失败,用户名:{}", userName);
        }
        view.addObject("outResponse", outResponse);

        return view;
    }
 

找回密码

@RequestMapping("/sendCheckCode")
    public OutResponse sendCheckCode(String email) {
        OutResponse outResponse = new OutResponse<>();
        try {
            System.out.println("--------------------kajsfdlkjaslkfd");
            userService.sendCheckCode(email);
            outResponse.setCode(CodeEnum.SUCCESS);
        } catch (BussinessException e) {
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error("验证码发送失败,邮箱:{}");
        } catch (Exception e) {
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error("验证码发送失败,邮箱:{}", email);
        }
        return outResponse;
    }
 

密码修改

  @RequestMapping("/findPassword.do")
    public OutResponse findPassworddo(String email, String password, String checkcode) {
        OutResponse outResponse = new OutResponse();
        try {
            userService.modifyPassword(email, password, checkcode);
            outResponse.setCode(CodeEnum.SUCCESS);
        } catch (BussinessException e) {
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error("密码修改失败,邮箱{}", email);
        } catch (Exception e) {
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error("密码修改失败,邮箱:{}", email);
        }
        return outResponse;
    }
 

User.java

public class User {
    private String userid;

    private String email;

    private String userName;

    private String password;

    private String userIcon;

    private String userBg;

    private String age;

    private String sex;

    private String characters;

    private Integer mark=0;

    private String address;

    private String work;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    
    private String birthdayString;
    
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
    private Date registerTime;

    private String registerTimeString;
    
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd", timezone="GMT+8")
    private Date lastLoginTime;

    private String lastLoginTimeString ;
    
    private String activationCode;

    private Integer status;

    private Integer userPage;
    
}
UserMapper.xml

插入邮箱地址信息


    insert into known_user (userid, email, user_name,
      password, user_icon, user_bg, birthday,
      register_time, last_login_time, activation_code)
    values (#{userid,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR},
      #{password,jdbcType=VARCHAR}, #{userIcon,jdbcType=VARCHAR}, #{userBg,jdbcType=VARCHAR}, 
      #{birthday,jdbcType=TIMESTAMP}, #{registerTime,jdbcType=TIMESTAMP},
      #{lastLoginTime,jdbcType=TIMESTAMP},#{activationCode,jdbcType=VARCHAR})
  

邮箱账户激活后更新账户信息

    
        update known_user set status = 1
        where user_name = #{userName,jdbcType=VARCHAR}
        and activation_code=#{activationCode,jdbcType=VARCHAR}
    
StringUtil.java

邮箱格式初步校验

//判断是否为邮箱
    public static boolean isEmail(String str) {
        String checkEmail = "^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
        if (!isEmpty(str)) {
            return str.matches(checkEmail);
        } else {
            return false;
        }
    }
UserService.java-接口
User findUserByEmail(String email);//邮箱找回
void sendCheckCode(String email) throws BussinessException;//发送验证码
void modifyPassword(String email, String password, String checkcode) throws BussinessException;//修改密码
UserServiceImpl.java-接口实现逻辑

发送激活邮件

   // 发送激活邮件
        String subject = "学生信息资源共享系统系统通知邮件";
        StringBuffer content = new StringBuffer("亲爱的 【" + user.getUserName() + "】用户

"); content.append("欢迎您使用学生信息资源共享系统!

"); content.append("点击 + mailConfig.getGlob_Real_Path() + "/user/activate?userName=" + user.getUserName() + "&activationCode=" + activationCode + "'>学生信息资源共享系统账号激活激活您的账号!"); try { MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email, subject, new String(content)); } catch (Exception e) { throw new BussinessException("发送邮件失败,请稍后再试"); }

效果图

通过用户名查找用户,校验是否激活并注册成功

public void updateUserActivate(String userName, String activationCode) throws BussinessException {

        //通过用户名查找用户
        User user = findUserByUserName(userName);
        if (user == null) {
            throw new BussinessException("用户【"+userName+"】不存在,请注册用户");
        }
        if (user.getUserPage() != 0) {
            throw new BussinessException("用户【"+userName+"】已激活, 请登录");
        }
        if (!activationCode.equals(user.getActivationCode())) {
            throw new BussinessException("用户【"+userName+"】激活码失效, 请使用最新激活链接");
        }
        userMapper.updateStatus(userName, activationCode);
    }

status为0代表账户未激活

 if (user.getStatus() == 0) {
            throw new BussinessException("请查收邮件, 激活账户后登录");
        }

邮箱验证码发送

 public void sendCheckCode(String email) throws BussinessException {
        if (StringUtil.isEmpty(email) || !StringUtil.isEmail(email)) {
            throw new BussinessException("输入参数不合法");
        }
        User user = findUserByEmail(email);

        if (user == null) {
            throw new BussinessException("邮箱不存在");
        }

        String checkCode = StringUtil.getActivationCode(6);

        String subject = "学生信息资源共享系统系统通知邮件";

        StringBuffer content = new StringBuffer("亲爱的 【" + user.getUserName() + "】用户

"); content.append("欢迎您使用+mailConfig.getGlob_Real_Path()+"'>学生信息资源共享系统的找回密码功能

"); content.append("您的验证码是

" + checkCode + ""); try { System.out.println("======================"+checkCode); MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email, subject, new String(content)); } catch (Exception e) { throw new BussinessException("发送邮件失败,请稍后再试"); } user.setActivationCode(checkCode); userMapper.update(user); }

用户有效性验证

  @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Integer changeMark(String userid, int mark) {
        return userMapper.changeUserMark(mark, userid);
    }

    public User findUserInfo4UserHome(String userId) throws BussinessException {
        
        User user = findUserByUserid(userId);
        if (user == null) {
            throw new BussinessException("用户不存在");
        }
        //设置密码为空
        user.setPassword(null);
        //设置激活码为空
        user.setActivationCode(null);
        return user;
    }

application-config设置发件人邮箱

mail.sendUserName=你的邮箱地址(推荐163)
mail.sendPassword=邮箱pop服务器地址
前端 注册
    

找回密码
 
找回密码

正在加载验证码......

请先拖动验证码到相应位置

返回进行登录 | 注册一个新账号

    var handlerEmbed = function (captchaObj) {
        $("#findpassword").click(function (e) {
            var validate = captchaObj.getValidate();
            if (!validate) {
                $("#notice")[0].className = "show";
                setTimeout(function () {
                    $("#notice")[0].className = "hide";
                }, 2000);
                e.preventDefault();     
            } else{
            	                var email = $('#email').val();
        		var emailreg = /^w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/;
        		if (email == null || $.trim(email) == '') {
        			checkForm('邮箱不能为空', 'email');
        			$("#email").parent().addClass('has-error');
        		} else if (!emailreg.test(email)) {
        			checkForm('请输入正确的邮箱', "email");
        			$("#email").parent().addClass('has-error');
        		} else {
        			$("#email").parent().removeClass('has-error');
        			var loadingindex = layer.load(0, {
        			  shade: [0.1,'#fff'] //0.1透明度的白色背景
        			});
        			$.ajax({
        				url: known.realpath + '/user/sendCheckCode',
        				type: 'POST',
        				dataType: 'json',
        				data: $('#findPassword').serialize(),
        				success: function(data) {
        					layer.close(loadingindex);
        					if (data.msg == null) {
        						var content = '
'; var d = dialog({ title: '修改密码', width: 300, content: content, okValue: '确定', ok: function() { 。。。 } else if (checkcode == null || $.trim(checkcode) == '') { $("#confirmPassword").parent().removeClass('has-error'); checkForm("验证码不能为空串", "checkcode"); $("#checkcode").parent().addClass('has-error'); return false; } else { $.ajax({ url: known.realpath+ '/user/findPassword.do', type: 'POST', dataType: 'json', data: { "email": email, "password": password, "checkcode": checkcode }, success: function(data) { if (data.msg == null) { var d = dialog({ content: " + known.realpath +"/resources/images/loading.gif' />   修改成功,跳转中...", }); d.showModal(); setTimeout(function() { d.close().remove(); document.location.href = known.realpath + "/user/login"; }, 1000); } else { checkForm(data.msg, "checkcode"); } } }); return false;

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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