(三)用户模型开发

1.otp验证码获取

   //用户获取otp短信接口
    @RequestMapping(value = "/getotp",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommenReturnType getOtp(@RequestParam(name="telphone") String telphone){
        //1. 按照一定的规则生成OPT验证码
        Random random = new Random();
        int randomInt = random.nextInt(99999);// [0,99999)
        randomInt += 10000;   //  [10000,109999]
        String otpCode = String.valueOf(randomInt);

        //2. 将OPT验证码与用户手机号相关联,使用HttpSession的方式(企业里使用分布式的Redis)
        httpServletRequest.getSession().setAttribute(telphone,otpCode);


        //3. 将OPT验证码通过短信通道发送给用户,省略(可够买第三方短信通道,以HTTP Post 方式发送)
        //企业里控制台输出是用log4j,这里方便调试,简单的把验证码输入控制台
        System.out.println("telphone = "+telphone+" & otpCode = "+otpCode);

        return CommenReturnType.create(null);

    }

2.用户注册

//用户注册接口
    @RequestMapping(value = "/register",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommenReturnType register(@RequestParam(name="telphone") String telphone,
                                     @RequestParam(name="otpCode") String otpCode,
                                     @RequestParam(name="password") String password,
                                     @RequestParam(name="name") String name,
                                     @RequestParam(name="gender") Integer gender,
                                     @RequestParam(name="age") Integer age) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //验证手机号和otpcode相符合
        String inSessionOtpCode = (String)this.httpServletRequest.getSession().getAttribute(telphone);
        if(!StringUtils.equals(otpCode,inSessionOtpCode)){
            throw new BusinessException(EmBussinessError.PARMETER_VALIDATION_ERROR,"短信验证码不符合");
        }
        //用户注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        //userModel.setGender(gender);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));

        userModel.setTelphone(telphone);
        userModel.setAge(age);
        userModel.setEncrptPassWord(this.EncodeByMd5(password));

        userService.register(userModel);

        return CommenReturnType.create(null);

    }

3.用户登录


    //用户登录接口
    @RequestMapping(value = "/login",method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommenReturnType login(@RequestParam(name="telphone") String telphone,
                                     @RequestParam(name="password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        if(StringUtils.isEmpty(telphone)||
                StringUtils.isEmpty(password)){
            throw new BusinessException(EmBussinessError.PARMETER_VALIDATION_ERROR);
        }

        //用户登录服务,用来校验用户登录是否合法
        UserModel userModel = userService.validateLogin(telphone,this.EncodeByMd5(password));

        //将登录凭证加入到用户登录成功的session内
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);

        return CommenReturnType.create(null);

    }

4.优化校验

(1) 检验结果

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class ValidationResult {
    //校验结果是否有错
    private boolean hasErrors = false;
    private Map errMsgMap = new HashMap<>();

    public boolean isHasErrors() {
        return hasErrors;
    }

    public void setHasErrors(boolean hasErrors) {
        this.hasErrors = hasErrors;
    }

    public Map getErrMsgMap() {
        return errMsgMap;
    }

    public void setErrMsgMap(Map errMsgMap) {
        this.errMsgMap = errMsgMap;
    }
    //实现通用的通过格式化字符串信息获取错误结果的msg的方法

    public  String getErrMsg(){
        return StringUtils.join(errMsgMap.values().toArray(),",");

    }
}

(2)校验器


import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Component
public class ValidatorImpl implements InitializingBean {

    private Validator validator;

    //实现校验方法并返回结果
    public ValidationResult validate(Object bean){
        final ValidationResult result = new ValidationResult();
        Set> constraintViolationSet = validator.validate(bean);
        if(constraintViolationSet.size()>0){
            //有错误
            result.setHasErrors(true);
            constraintViolationSet.forEach(constraintViolation->{
                String errMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                result.getErrMsgMap().put(propertyName,errMsg);
            });
        }
        return result;


    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //将hibernate validator 通过工厂的初始化方式使其实例化
        this.validator = (Validator) Validation.buildDefaultValidatorFactory().getValidator();
    }
}

你可能感兴趣的:((三)用户模型开发)