SpringBoot构建电商基础秒杀项目总结

用户登录功能实现

1、UserController.java修改

//用户登录接口
    @RequestMapping(value = "/login", method = {
     RequestMethod.POST}, consumes = {
     CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType 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(EmBusinessError.PARAMETER_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 CommonReturnType.create(null);

    }

2、UserDOMapper.xml

新加一个查询语句

  <select id="selectByTelphone"  resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from user_info
    where telphone = #{telphone,jdbcType=VARCHAR}
  select>

3、UserDOMapper接口

    UserDO selectByTelphone(String telphone);

4、UserService接口

/**
     * @param telphone 用户注册手机
     * @param encrptPassword 用户加密后的密码
     * @return
     * @throws BusinessException
     */
    UserModel validateLogin(String telphone, String encrptPassword) throws BusinessException;

5、EmBusinessError枚举

public enum EmBusinessError implements CommonError{
     
    //通用错误类型10001
    PARAMETER_VALIDATION_ERROR(10001, "参数不合法"),
    UNKNOWN_ERROR(10002,"未知错误"),
    //20000开头为用户信息相关错误定义
    USER_NOT_EXIST(20001, "用户不存在"),
    //30000开头为用户登录相关错误定义
    USER_LOGIN_FAIL(30001, "用户手机号或密码不正确");
    ;

6、UserServiceImpl.java

 @Override
    public UserModel validateLogin(String telphone, String encrptPassword) throws BusinessException {
     
        //通过用户手机获取用户信息
        UserDO userDO = userDOMapper.selectByTelphone(telphone);
        if (userDO == null) {
     
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        UserPasswordDO userPasswordDO = userPasswordDOMapper.selectByUserId(userDO.getId());
        UserModel userModel = convertFromDataObject(userDO, userPasswordDO);
        //比对用户信息内加密的密码是否和传输进来的密码相匹配
        if (!StringUtils.equals(encrptPassword, userModel.getEncrptPassword())) {
     
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        return userModel;
    }

7、login.html 将login界面放入webstrom软件运行,才能解决跨域请求问题

<html>
<head>
    <meta charset="UTF-8">

    <link href="static/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="static/assets/global/plugins/css/component.css" rel="stylesheet" type="text/css"/>
    <link href="static/assets/admin/pages/css/login.css" rel="stylesheet" type="text/css"/>
    <script src="static/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript">script>
    <title>Titletitle>
head>
<body class="login">
    <div class="content">
        <h3 class="form-title">用户登录h3>
        <div class="form-group">
            <label class="control-label">手机号label>
            <div>
                <input class="form-control" type="text" placeholder="手机号" name="telphone" id="telphone"/>
            div>
        div>
        <div class="form-group">
            <label class="control-label">密码label>
            <div>
                <input class="form-control" type="password" placeholder="密码" name="password" id="password"/>
            div>
        div>
        <div class="form-actions">
            <button class="btn blue" id="login" type="submit">
                登录
            button>
            <button class="btn green" id="register" type="submit">
                注册
            button>
        div>
    div>

body>

<script>
    jQuery(document).ready(function () {
       
        //绑定注册按钮的click事件用于跳转到注册页面
        $("#register").on("click",function () {
       
            window.location.href = "getotp.html";
        });
        //绑定登录按钮的click事件用于登录
        $("#login").on("click",function () {
       

            var telphone=$("#telphone").val();
            var password=$("#password").val();
            if (telphone==null || telphone=="") {
       
                alert("手机号不能为空");
                return false;
            }
            if (password==null || password=="") {
       
                alert("密码不能为空");
                return false;
            }
            //映射到后端@RequestMapping(value = "/login", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
            $.ajax({
       
                type:"POST",
                contentType:"application/x-www-form-urlencoded",
                url:"http://localhost:8090/user/login",
                data:{
       
                    "telphone":telphone,
                    "password":password
                },
                //允许跨域请求
                xhrFields:{
       withCredentials:true},
                success:function (data) {
       
                    if (data.status=="success") {
       
                        alert("登录成功");
                    }else {
       
                        alert("登录失败,原因为" + data.data.errMsg);
                    }
                },
                error:function (data) {
       
                    alert("登录失败,原因为"+data.responseText);
                }
            });
            return false;
        });
    });
script>
html>

8、运行测试

SpringBoot构建电商基础秒杀项目总结_第1张图片
SpringBoot构建电商基础秒杀项目总结_第2张图片

优化校验规则

pom.xml

<dependency>
  <groupId>org.hibernategroupId>
  <artifactId>hibernate-validatorartifactId>
  <version>5.2.4.Finalversion>
dependency>

对validator进行一个简单的封装

1、新建validator的目录

新建一个ValidationResult的类
ValidationResult.java

public class ValidationResult {
     
    //校验结果是否有错
    private boolean hasErrors = false;
    //存放错误信息的map
    private Map<String, String> errorMsgMap = new HashMap<>();
    public boolean isHasErrors() {
     
        return hasErrors;
    }
    public void setHasErrors(boolean hasErrors) {
     
        this.hasErrors = hasErrors;
    }
    public Map<String, String> getErrorMsgMap() {
     
        return errorMsgMap;
    }
    public void setErrorMsgMap(Map<String, String> errorMsgMap) {
     
        this.errorMsgMap = errorMsgMap;
    }
    //实现通用的通过格式化字符串信息获取错误结果的msg方法
    public String getErrMsg() {
     
        return StringUtils.join(errorMsgMap.values().toArray(), ",");
    }
}

新建一个ValidatorImpl的类
ValidatorImpl.java

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<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
        if (constraintViolationSet.size() > 0) {
     
            //有错误
            result.setHasErrors(true);
            constraintViolationSet.forEach(constraintViolation ->{
     
                String errMsg = constraintViolation.getMessage();
                String propertyName = constraintViolation.getPropertyPath().toString();
                result.getErrorMsgMap().put(propertyName, errMsg);
            });
        }
        return result;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
     
        //将hibernate validator通过工厂的初始化方式使其实例化
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
}
2、UserModel.java重新修改
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class UserModel {
     
    private Integer id;
    @NotBlank(message = "用户名不能为空")
    private String name;
    @NotNull(message = "性别不能填写")
    private Byte gender;
    @NotNull(message = "年龄不能不填写")
    @Min(value = 0, message = "年龄必须大于0岁")
    @Max(value = 150, message = "年龄必须小于150岁")
    private Integer age;
    @NotBlank(message = "手机号不能为空")
    private String telphone;
    private String registerMode;
    private Integer thirdPartyId;
    @NotBlank(message = "密码不能为空")
    private String encrptPassword;
    //getset方法自行添加
}
3、UserServiceImpl.java

首先注入ValidatorImpl

    @Autowired
    private ValidatorImpl validator;

修改register方法:

@Override
    @Transactional//声明事务
    public void register(UserModel userModel) throws BusinessException {
     
        //校验
        if (userModel == null) {
     
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
/*
        if (StringUtils.isEmpty(userModel.getName())
                || userModel.getGender() == null
                || userModel.getAge() == null
                || StringUtils.isEmpty(userModel.getTelphone())) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
*/
        ValidationResult result = validator.validate(userModel);
        if (result.isHasErrors()){
     
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }
        //实现model->dataobject方法
        UserDO userDO = convertFromModel(userModel);
        try {
     
            //insertSelective相对于insert方法,不会覆盖掉数据库的默认值
            userDOMapper.insertSelective(userDO);
        }catch (DuplicateKeyException ex){
      //手机号码出现唯一索引的异常
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"手机号已重复注册");
        }
        userModel.setId(userDO.getId());
        UserPasswordDO userPasswordDO = convertPasswordFromModel(userModel);
        userPasswordDOMapper.insertSelective(userPasswordDO);
        return;
    }
4、重新运行

SpringBoot构建电商基础秒杀项目总结_第3张图片

你可能感兴趣的:(springboot,maven,mysql,spring,boot,mysql)