当前位置:网站首页>Data and information resource sharing platform (VIII)

Data and information resource sharing platform (VIII)

2022-06-10 23:29:00 yyDrifter

principle

Set two fields in the database ,status:(0: not active ,1: Activation successful ),activition_code:( Release activation code ):
 Insert picture description here
The user fills in the information , Click registration , Insert data succeeded ,state The default field is 0, Generate a activition_code( Use the e-mail you sent me 、 password 、 And the current time ) Also stored in the database .
Send E-mail , Prompt the user to log in to the mailbox to activate , There is an activation success page in the email URL,URL There are two parameters ( user ID And activation code ).
The user logs in to the mailbox and clicks the link , Go to the process activated business logic page or Servlet, obtain URL Two parameters in , Query the data in the database based on these two parameters , If there is , Check whether the activation code transmitted from the link is consistent with the database field activation code , atypism , Delete this record in the database , And jump to the activation failure interface , Agreement , The field state by 1, Activation successful , Go to the activation success page .

Back end

UserController.java

Email registration

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

        OutResponse<Object> 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 registration failed , user name :{} mailbox :{}", user.getUserName(), user.getEmail());
        } catch (Exception e) {
    
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error(" User registration failed , user name :{} mailbox :{}", user.getUserName(), user.getEmail());
        }
        return outResponse;
    }

Email account activation

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

        OutResponse<Object> outResponse = new OutResponse<>();
        ModelAndView view = new ModelAndView("/page/active");
        try {
    
            userService.updateUserActivate(userName, activationCode);
            outResponse.setCode(CodeEnum.SUCCESS);
            outResponse.setMsg(" honorific 【"+userName+"】 user , Congratulations on your successful account activation ");
        } catch (BussinessException e) {
    
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error(" User activation failed , user name :{}", userName);
        } catch (Exception e) {
    
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error(" User activation failed , user name :{}", userName);
        }
        view.addObject("outResponse", outResponse);

        return view;
    }

Retrieve password

@RequestMapping("/sendCheckCode")
    public OutResponse<Object> sendCheckCode(String email) {
    
        OutResponse<Object> 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(" Verification code sending failed , mailbox :{}");
        } catch (Exception e) {
    
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error(" Verification code sending failed , mailbox :{}", email);
        }
        return outResponse;
    }

Password change

  @RequestMapping("/findPassword.do")
    public OutResponse<Object> findPassworddo(String email, String password, String checkcode) {
    
        OutResponse<Object> outResponse = new OutResponse<Object>();
        try {
    
            userService.modifyPassword(email, password, checkcode);
            outResponse.setCode(CodeEnum.SUCCESS);
        } catch (BussinessException e) {
    
            outResponse.setMsg(e.getLocalizedMessage());
            outResponse.setCode(CodeEnum.BUSSINESSERROR);
            logger.error(" Password change failed , mailbox {}", email);
        } catch (Exception e) {
    
            outResponse.setMsg(CodeEnum.SERVERERROR.getDesc());
            outResponse.setCode(CodeEnum.SERVERERROR);
            logger.error(" Password change failed , mailbox :{}", 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 email address information

<insert id="insert" parameterType="com.known.common.model.User" >
    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})
  </insert>

Update the account information after the email account is activated

    <update id="updateStatus">
        update known_user set status = 1
        where user_name = #{
    userName,jdbcType=VARCHAR}
        and activation_code=#{
    activationCode,jdbcType=VARCHAR}
    </update>

StringUtil.java

Preliminary verification of mailbox format

// Judge whether it is a mailbox 
    public static boolean isEmail(String str) {
    
        String checkEmail = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
        if (!isEmpty(str)) {
    
            return str.matches(checkEmail);
        } else {
    
            return false;
        }
    }

UserService.java- Interface

User findUserByEmail(String email);// Get the mailbox back 
void sendCheckCode(String email) throws BussinessException;// Send verification code 
void modifyPassword(String email, String password, String checkcode) throws BussinessException;// Change Password 

UserServiceImpl.java- Interface implementation logic

Send activation email

   //  Send activation email 
        String subject = " Student information resource sharing system system notification email ";
        StringBuffer content = new StringBuffer(" dear  【" + user.getUserName() + "】 user <br><br>");
        content.append(" Welcome to the student information resource sharing system !<br><br>");
        content.append(" Click on <a href='" + mailConfig.getGlob_Real_Path() + "/user/activate?userName=" + user.getUserName() +
                "&activationCode=" + activationCode + "'> Student information resource sharing system account activation </a> Activate your account !");
        try {
    
            MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
                    subject, new String(content));
        } catch (Exception e) {
    
            throw new BussinessException(" Failed to send email , Please try again later ");
        }

design sketch
 Insert picture description here
Search for users by user name , Verify whether activation and registration are successful

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

        // Search for users by user name 
        User user = findUserByUserName(userName);
        if (user == null) {
    
            throw new BussinessException(" user 【"+userName+"】 non-existent , Please register the user ");
        }
        if (user.getUserPage() != 0) {
    
            throw new BussinessException(" user 【"+userName+"】 Activated ,  Please log in ");
        }
        if (!activationCode.equals(user.getActivationCode())) {
    
            throw new BussinessException(" user 【"+userName+"】 The activation code is invalid ,  Please use the latest activation link ");
        }
        userMapper.updateStatus(userName, activationCode);
    }

status by 0 Represents that the account is not activated

 if (user.getStatus() == 0) {
    
            throw new BussinessException(" Please check your email ,  Log in after activating the account ");
        }

Email verification code sent

 public void sendCheckCode(String email) throws BussinessException {
    
        if (StringUtil.isEmpty(email) || !StringUtil.isEmail(email)) {
    
            throw new BussinessException(" Illegal input parameter ");
        }
        User user = findUserByEmail(email);

        if (user == null) {
    
            throw new BussinessException(" The mailbox doesn't exist ");
        }

        String checkCode = StringUtil.getActivationCode(6);

        String subject = " Student information resource sharing system system notification email ";

        StringBuffer content = new StringBuffer(" dear  【" + user.getUserName() + "】 user <br><br>");
        content.append(" Welcome to <a href='"+mailConfig.getGlob_Real_Path()+"'> Student information resource sharing system </a> Password retrieval function of <br><br>");
        content.append(" Your verification code is <h3 style='color:red;'>" + checkCode + "</h3>");
        try {
    
            System.out.println("======================"+checkCode);
            MailUtil.sendMail(mailConfig.getSendUserName(), mailConfig.getSendPassword(), email,
                    subject, new String(content));
        } catch (Exception e) {
    
            throw new BussinessException(" Failed to send email , Please try again later ");
        }
        user.setActivationCode(checkCode);
        userMapper.update(user);
    }

User validation

  @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(" The user doesn't exist ");
        }
        // Set password to blank 
        user.setPassword(null);
        // Set the activation code to null 
        user.setActivationCode(null);
        return user;
    }

application-config Set the sender's mailbox

mail.sendUserName= Your email address ( recommend 163)
mail.sendPassword= mailbox pop Server address 

front end

register

    <div class="form-group">
                    <label class="col-lg-2 control-label"> mailbox :</label>
                    <div class="col-lg-10">
                        <input type="text" class="form-control" name="email" id="email" placeholder=" Used to retrieve the password , Please fill in the correct email address ">
                    </div>
                </div>

 Insert picture description here

Retrieve password

 <div class="container-findpassword">
        <div class="findpassword">
            <div>
               <legend class="form_legend">
         		 Retrieve password 
		        </legend>
                <form id="findPassword">
                    <div class="form-group">
                        <input class="form-control" placeholder=" Please enter email address " name="email" id="email"></input>
                </div>
                <div class="form-group" >
                    <div id="embed-captcha"></div>
                    <p id="wait" class="show"> Loading captcha ......</p>
                    <p id="notice" class="hide"> Please drag the verification code to the corresponding position </p>
                </div>
            </form>
            <div class="form-group">
                <button type="button" class="btn btn-info block full-width" id="findpassword"> Send verification code </button>
            </div>
            <p class="foot">
                <a href="${realpath}/user/login"> Return to log in </a>
                |
                <a href="${realpath}/user/register"> Sign up for a new account </a>
            </p>
        </div>
    </div>
    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(' The mailbox cannot be empty ', 'email');
        			$("#email").parent().addClass('has-error');
        		} else if (!emailreg.test(email)) {
    
        			checkForm(' Please enter the correct email ', "email");
        			$("#email").parent().addClass('has-error');
        		} else {
    
        			$("#email").parent().removeClass('has-error');
        			var loadingindex = layer.load(0, {
    
        			  shade: [0.1,'#fff'] //0.1 Transparent white background 
        			});
        			$.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 = '<form id="modifyPassword"><div class="form-group"><input class="form-control" type="password" placeholder=" Please enter the new password " name="password" id="password"></input></div><div class="form-group"><input class="form-control" type="password" placeholder=" Please confirm the new password " name="confirmPassword" id="confirmPassword"></input></div><div class="form-group"><input class="form-control" placeholder=" Verification Code " name="checkcode" id="checkcode"></input></div></form>';
        						var d = dialog({
    
        							title: ' Change Password ',
        							width: 300,
        							content: content,
        							okValue: ' determine ',
        							ok: function() {
    
        								...
        								} else if (checkcode == null || $.trim(checkcode) == '') {
    
        									$("#confirmPassword").parent().removeClass('has-error');
        									checkForm(" The verification code cannot be an empty string ", "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: "<div><img src='" + known.realpath +"/resources/images/loading.gif' />&nbsp;&nbsp;&nbsp; Modification successful , Jumping ...</div>",
        												});
        												d.showModal();
        												setTimeout(function() {
    
        													d.close().remove();
        													document.location.href = known.realpath + "/user/login";
        												}, 1000);
        											} else {
    
        												checkForm(data.msg, "checkcode");
        											}
        										}
        									});
        									return false;

 Insert picture description here

原网站

版权声明
本文为[yyDrifter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102158001238.html