Mall - User Registration - Registration function

6. registration function

6.1. Interface Description

Here Insert Picture Description

6.2.controller

/**
 * 注册
 * @param user
 * @param code
 * @return
 */
@PostMapping("register")
public ResponseEntity<Void> register(User user, @RequestParam("code") String code) {
    Boolean boo = this.userService.register(user, code);
    if (boo == null || !boo) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}

6.3.service

The basic logic:

  • 1) check codes SMS
  • 2) salt formation
  • 3) to encrypt the password
  • 4) into the database
  • 5) Delete Redis verification code
public Boolean register(User user, String code) {
    String key = KEY_PREFIX + user.getPhone();
    // 从redis取出验证码
    String codeCache = this.redisTemplate.opsForValue().get(key);
    // 检查验证码是否正确
    if (!code.equals(codeCache)) {
        // 不正确,返回
        return false;
    }
    user.setId(null);
    user.setCreated(new Date());
    // 生成盐
    String salt = CodecUtils.generateSalt();
    user.setSalt(salt);
    // 对密码进行加密
    user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
    // 写入数据库
    boolean boo = this.userMapper.insertSelective(user) == 1;

    // 如果注册成功,删除redis中的code
    if (boo) {
        try {
            this.redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error("删除缓存验证码失败,code:{}", code, e);
        }
    }
    return boo;
}

6.4. Test

We RestClient test:
Here Insert Picture Description

View database:
Here Insert Picture Description

6.5. Verification data server

Although just realized the registration, but the server does not perform data validation, and verification front end is easily bypassed by caring people. So we have to add data validation functions in the background:

Here we will use Hibernate-Validator framework has verified the data:

The SpringBoot the web starter has integrated its dependencies:
Here Insert Picture Description

6.5.1. What is Hibernate Validator

Hibernate Validator is an open source framework Hibernate provides a very handy implement server-side data validation using annotation mode.

Official website: http://hibernate.org/validator/
Here Insert Picture Description

hibernate Validator is a reference implementation of the Bean Validation.

Hibernate Validator provides all realize the built-in constraint (constraint) of the JSR 303 specification, in addition to some additional constraint.

In the daily development, Hibernate Validator is often used to verify the bean field, the explanatory notes, convenient and efficient.

6.5.2.Bean check notes

Common annotated as follows:

Constraint details
@Valid Annotated element is an object, all fields need to check the value of this object
@Null The annotated element must be null
@NotNull The annotated element must not be null
@AssertTrue The element being annotated must be true
@AssertFalse The element being annotated must be false
@Min(value) Annotated element must be a number whose value must be greater than the specified minimum
@Max(value) Annotated element must be a number which must be less than the maximum value equal to the specified
@DecimalMin(value) Annotated element must be a number whose value must be greater than the specified minimum
@DecimalMax(value) Annotated element must be a number which must be less than the maximum value equal to the specified
@Size(max, min) The size of the element to be annotated in a specified range
@Digits (integer, fraction) Annotated element must be a number whose value must be within an acceptable range
@Past The annotated element must be a date in the past
@Future The annotated element must be a future date
@Pattern(value) The element being annotated must meet the specified regular expression
@Email The annotated element must be the e-mail address
@Length Note the size of the string must be within a specified range
@NotEmpty Annotated string must not be null
@Range Elements must be annotated in the range of appropriate
@NotBlank Annotated string must not be null
@URL(protocol=,host=, port=,regexp=, flags=) Annotated string must be a valid url
@CreditCardNumber The string must be annotated by algorithm Luhn check, bank cards, credit cards and other numbers are generally calculated using Luhn legitimacy

6.5.3. Add User to check

We ly-user-interfaceadd the Hibernate-Validator-dependent:

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

We add annotations on the part of the property of the User object:

@Table(name = "tb_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Length(min = 4, max = 30, message = "用户名只能在4~30位之间")
    private String username;// 用户名

    @JsonIgnore
    @Length(min = 4, max = 30, message = "用户名只能在4~30位之间")
    private String password;// 密码

    @Pattern(regexp = "^1[35678]\\d{9}$", message = "手机号格式不正确")
    private String phone;// 电话

    private Date created;// 创建时间

    @JsonIgnore
    private String salt;// 密码的盐值
}

6.5.4. Be controlled from the controller

In the controller just to give User can add @Valid comment.
Here Insert Picture Description

6.5.5. Test

We deliberately incorrectly:
Here Insert Picture Description

SpringMVC then automatically returns the error message:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/shenzhen_zsw/article/details/92775509