mirror of
				https://gitee.com/coder-xiaomo/flashsale
				synced 2025-11-04 22:23:14 +08:00 
			
		
		
		
	优化校验规则
This commit is contained in:
		
							
								
								
									
										48
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										48
									
								
								README.md
									
									
									
									
									
								
							@@ -14,28 +14,30 @@
 | 
			
		||||
 | 
			
		||||
### 层次结构(以User为例,自上向下)
 | 
			
		||||
 | 
			
		||||
|                   | 目录                    | Java对象类型                        | 说明                            | 举例                           |
 | 
			
		||||
|-------------------|-----------------------|---------------------------------|-------------------------------|------------------------------|
 | 
			
		||||
| **Controller层**   |                       |                                 |                               |                              |
 | 
			
		||||
| Controller        | controller            | 类 class                         |                               | controller.UserController    |
 | 
			
		||||
| View Object       | controller/viewobject | 类 class                         | 将用户Model转化为可供UI使用的View Object | controller.UserController    |
 | 
			
		||||
|                   |                       |                                 |                               |                              |
 | 
			
		||||
| **Service层**      | 转换成业务模型               |                                 |                               |                              |
 | 
			
		||||
| Service           | service               | 接口 interface                    |                               | service.UserService          |
 | 
			
		||||
| ServiceImpl       | service/impl          | Service接口实现类                    | 将DataObject组装成Model           | service.impl.UserServiceImpl |
 | 
			
		||||
| Model             | service/model         | 类 class                         | 用户模型Model                     | service.model.UserModel      |
 | 
			
		||||
|                   |                       |                                 |                               |                              |
 | 
			
		||||
| **Dao层**          | 对数据库的映射               |                                 |                               |                              |
 | 
			
		||||
| Mapper            | dao                   | 接口 interface                    |                               | dao.UserDOMapper             |
 | 
			
		||||
| Mapping           | resources/mapping     | Mapper接口实现类                     | xml格式;SQL语句                   | mapping/UserDOMapper.xml     |
 | 
			
		||||
| Data Object       | dataobject            | 类 class                         |                               | dataobject.UserDO            |
 | 
			
		||||
|                   |                       |                                 |                               |                              |
 | 
			
		||||
| **其他**            |                       |                                 |                               |                              |
 | 
			
		||||
| response          | response              |                                 | 用于处理HTTP请求返回                  | response.CommonReturnType    |
 | 
			
		||||
|                   |                       |                                 |                               |                              |
 | 
			
		||||
| **异常处理**          | 用于返回错误信息              |                                 |                               |                              |
 | 
			
		||||
| CommonError       | error                 | 接口 interface                    |                               | error.CommonError            |
 | 
			
		||||
| EmBusinessError   | error                 | 枚举 enum & CommonError接口实现类      |                               | error.EmBusinessError        |
 | 
			
		||||
| BusinessException | error                 | CommonError接口实现类 & 继承自Exception |                               | error.BusinessException      |
 | 
			
		||||
|                   | 目录                  | Java对象类型                            | 说明                                     | 举例                            |
 | 
			
		||||
| ----------------- | --------------------- | --------------------------------------- | ---------------------------------------- | ------------------------------- |
 | 
			
		||||
| **Controller层**  |                       |                                         |                                          |                                 |
 | 
			
		||||
| Controller        | controller            | 类 class                                |                                          | controller.UserController       |
 | 
			
		||||
| View Object       | controller/viewobject | 类 class                                | 将用户Model转化为可供UI使用的View Object | controller.UserController       |
 | 
			
		||||
|                   |                       |                                         |                                          |                                 |
 | 
			
		||||
| **Service层**     | 转换成业务模型        |                                         |                                          |                                 |
 | 
			
		||||
| Service           | service               | 接口 interface                          |                                          | service.UserService             |
 | 
			
		||||
| ServiceImpl       | service/impl          | Service接口实现类                       | 将DataObject组装成Model                  | service.impl.UserServiceImpl    |
 | 
			
		||||
| Model             | service/model         | 类 class                                | 用户模型Model                            | service.model.UserModel         |
 | 
			
		||||
|                   |                       |                                         |                                          |                                 |
 | 
			
		||||
| **Dao层**         | 对数据库的映射        |                                         |                                          |                                 |
 | 
			
		||||
| Mapper            | dao                   | 接口 interface                          |                                          | dao.UserDOMapper                |
 | 
			
		||||
| Mapping           | resources/mapping     | Mapper接口实现类                        | xml格式;SQL语句                         | mapping/UserDOMapper.xml        |
 | 
			
		||||
| Data Object       | dataobject            | 类 class                                |                                          | dataobject.UserDO               |
 | 
			
		||||
|                   |                       |                                         |                                          |                                 |
 | 
			
		||||
| **其他**          |                       |                                         |                                          |                                 |
 | 
			
		||||
| response          | response              |                                         | 用于处理HTTP请求返回                     | response.CommonReturnType       |
 | 
			
		||||
| ValidationResult  | validator             | 类 class                                | Hibernate Validator 参数验证             | validator\ValidationResult.java |
 | 
			
		||||
| ValidatorImpl     | validator             | ValidationResult类实现类                | Hibernate Validator 参数验证             | validator\ValidatorImpl.java    |
 | 
			
		||||
|                   |                       |                                         |                                          |                                 |
 | 
			
		||||
| **异常处理**      | 用于返回错误信息      |                                         |                                          |                                 |
 | 
			
		||||
| CommonError       | error                 | 接口 interface                          |                                          | error.CommonError               |
 | 
			
		||||
| EmBusinessError   | error                 | 枚举 enum & CommonError接口实现类       |                                          | error.EmBusinessError           |
 | 
			
		||||
| BusinessException | error                 | CommonError接口实现类 & 继承自Exception |                                          | error.BusinessException         |
 | 
			
		||||
 | 
			
		||||
**Tips:** Model与Data Object并非完全一一对应,例如UserModel是由ServiceImpl将UserDO和UserPasswordDO组装而成的。
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										17
									
								
								pom.xml
									
									
									
									
									
								
							
							
						
						
									
										17
									
								
								pom.xml
									
									
									
									
									
								
							@@ -65,6 +65,13 @@
 | 
			
		||||
            <artifactId>commons-lang3</artifactId>
 | 
			
		||||
            <version>3.7</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
 | 
			
		||||
        <!--参数验证-->
 | 
			
		||||
        <dependency>
 | 
			
		||||
            <groupId>org.hibernate</groupId>
 | 
			
		||||
            <artifactId>hibernate-validator</artifactId>
 | 
			
		||||
            <version>5.4.3.Final</version>
 | 
			
		||||
        </dependency>
 | 
			
		||||
    </dependencies>
 | 
			
		||||
 | 
			
		||||
    <build>
 | 
			
		||||
@@ -152,6 +159,16 @@
 | 
			
		||||
                </plugin>
 | 
			
		||||
            </plugins>
 | 
			
		||||
        </pluginManagement>
 | 
			
		||||
        <plugins>
 | 
			
		||||
            <plugin>
 | 
			
		||||
                <groupId>org.apache.maven.plugins</groupId>
 | 
			
		||||
                <artifactId>maven-compiler-plugin</artifactId>
 | 
			
		||||
                <configuration>
 | 
			
		||||
                    <source>8</source>
 | 
			
		||||
                    <target>8</target>
 | 
			
		||||
                </configuration>
 | 
			
		||||
            </plugin>
 | 
			
		||||
        </plugins>
 | 
			
		||||
    </build>
 | 
			
		||||
 | 
			
		||||
    <!--
 | 
			
		||||
 
 | 
			
		||||
@@ -8,6 +8,8 @@ import com.cxyxiaomo.flashsale.error.BusinessException;
 | 
			
		||||
import com.cxyxiaomo.flashsale.error.EmBusinessError;
 | 
			
		||||
import com.cxyxiaomo.flashsale.service.UserService;
 | 
			
		||||
import com.cxyxiaomo.flashsale.service.model.UserModel;
 | 
			
		||||
import com.cxyxiaomo.flashsale.validator.ValidationResult;
 | 
			
		||||
import com.cxyxiaomo.flashsale.validator.ValidatorImpl;
 | 
			
		||||
import org.apache.commons.lang3.StringUtils;
 | 
			
		||||
import org.springframework.beans.BeanUtils;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
@@ -20,9 +22,13 @@ public class UserServiceImpl implements UserService {
 | 
			
		||||
 | 
			
		||||
    @Autowired
 | 
			
		||||
    private UserDOMapper userDOMapper;
 | 
			
		||||
 | 
			
		||||
    @Autowired
 | 
			
		||||
    private UserPasswordDOMapper userPasswordDOMapper;
 | 
			
		||||
 | 
			
		||||
    @Autowired
 | 
			
		||||
    private ValidatorImpl validator;
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public UserModel getUserById(Integer id) {
 | 
			
		||||
        // 调用UserDataObjectMapper获取到对应的用户DataObject
 | 
			
		||||
@@ -60,11 +66,11 @@ public class UserServiceImpl implements UserService {
 | 
			
		||||
        if (userModel == null) {
 | 
			
		||||
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
 | 
			
		||||
        }
 | 
			
		||||
        if (StringUtils.isEmpty(userModel.getName())
 | 
			
		||||
                || userModel.getGender() == null
 | 
			
		||||
                || userModel.getAge() == null
 | 
			
		||||
                || StringUtils.isEmpty(userModel.getTelephone())) {
 | 
			
		||||
            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 方法
 | 
			
		||||
 
 | 
			
		||||
@@ -1,14 +1,33 @@
 | 
			
		||||
package com.cxyxiaomo.flashsale.service.model;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import javax.validation.constraints.Max;
 | 
			
		||||
import javax.validation.constraints.Min;
 | 
			
		||||
import javax.validation.constraints.NotBlank;
 | 
			
		||||
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 telephone;
 | 
			
		||||
 | 
			
		||||
    private String registerMode;
 | 
			
		||||
 | 
			
		||||
    private String thirdPartyId;
 | 
			
		||||
 | 
			
		||||
    @NotBlank(message = "密码不能为空")
 | 
			
		||||
    private String encryptPassword;
 | 
			
		||||
 | 
			
		||||
    public Integer getId() {
 | 
			
		||||
 
 | 
			
		||||
@@ -0,0 +1,35 @@
 | 
			
		||||
package com.cxyxiaomo.flashsale.validator;
 | 
			
		||||
 | 
			
		||||
import org.apache.commons.lang3.StringUtils;
 | 
			
		||||
 | 
			
		||||
import java.util.HashMap;
 | 
			
		||||
import java.util.Map;
 | 
			
		||||
 | 
			
		||||
public class ValidationResult {
 | 
			
		||||
    // 校验结果是否有错
 | 
			
		||||
    private boolean hasErrors = false;
 | 
			
		||||
 | 
			
		||||
    // 存放错误信息的Map
 | 
			
		||||
    private Map<String, String> errMsgMap = new HashMap<>();
 | 
			
		||||
 | 
			
		||||
    // 实现通用的通过格式化字符串信息获取错误结果的msg方法
 | 
			
		||||
    public String getErrMsg() {
 | 
			
		||||
        return StringUtils.join(errMsgMap.values().toArray(), ",");
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public boolean isHasErrors() {
 | 
			
		||||
        return hasErrors;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public void setHasErrors(boolean hasErrors) {
 | 
			
		||||
        this.hasErrors = hasErrors;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public Map<String, String> getErrMsgMap() {
 | 
			
		||||
        return errMsgMap;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public void setErrMsgMap(Map<String, String> errMsgMap) {
 | 
			
		||||
        this.errMsgMap = errMsgMap;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,37 @@
 | 
			
		||||
package com.cxyxiaomo.flashsale.validator;
 | 
			
		||||
 | 
			
		||||
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) {
 | 
			
		||||
        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.getErrMsgMap().put(propertyName, errMsg);
 | 
			
		||||
            });
 | 
			
		||||
        }
 | 
			
		||||
        return result;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public void afterPropertiesSet() throws Exception {
 | 
			
		||||
        // 将Hibernate Validator通过工厂的初始化方式使其实例化
 | 
			
		||||
        this.validator = (Validator) Validation.buildDefaultValidatorFactory().getValidator();
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user