java - When SpringMVC integrates hibernate validator for parameter verification, why doesn't it throw an exception directly?
天蓬老师
天蓬老师 2017-06-23 09:13:55
0
2
926

Hello everyone, I have a question

1. Environment

spring 4.3.7
hibernate-validator-5.4.1

2. The configuration is as follows

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource" name="messageSource">
        <property name="basenames">
            <list>
                <value>classpath:messages/messages</value>
                <value>classpath:messages/ValidationMessages</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage" value="false" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="cacheSeconds" value="60" />
    </bean>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        <property name="validationMessageSource" ref="messageSource"/>
    </bean>
    
    
    <mvc:annotation-driven validator="validator" />

3.bean and Controller

public class UserRequest {
    
    @NotBlank(message = "{login.valid.username.notnull}")
    private String username;
    
    @NotBlank(message = "{login.valid.password.notnull}")
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@Valid @RequestBody UserRequest ur, BindingResult result, HttpServletRequest request) {
        
        log.debug("login");
        
        if(result.hasErrors()) {  
            return result.getAllErrors().get(0);  
        } 
        
        ……
    }

Question:
Why must we use result.hasErrors() to display judgment in the code?
Isn’t it more reasonable to verify that the fields in UserRequest do not meet the definition and just throw an exception directly?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
Peter_Zhu

Question:
Why must we use result.hasErrors() to display judgment in the code?
Isn’t it more reasonable to verify that the fields in UserRequest do not meet the definition and just throw an exception directly?

For example, when a parameter exception occurs, what we return to the front end is the specific parameter name and description of the exception, not all the exception information given by Spring. If Spring automatically throws an exception, then it is difficult for you to control the returned information.

@PostMapping(UriView.REST_KNOWLEDGE_POINTS)
@ResponseBody
public Result createKnowledgePoint(@Valid KnowledgePoint knowledgePoint, BindingResult bindingResult) {
    // 如有参数错误,则返回错误信息给客户端
    if (bindingResult.hasErrors()) {
        return Result.fail(CommonUtils.getBindingMessage(bindingResult));
    }

    knowledgePoint.setKnowledgePointId(CommonUtils.uuid());
    knowledgePoint.setName(knowledgePoint.getName().trim());
    mapper.createKnowledgePoint(knowledgePoint);

    return Result.ok("", knowledgePoint);
}

/**
 * BindingResult 中的错误信息很多,对用户不够友好,使用 getBindingMessage()
 * 提取对用户阅读友好的定义验证规则 message。
 *
 * @param result 验证的结果对象
 * @return 验证规则 message
 */
public static String getBindingMessage(BindingResult result) {
    StringBuffer sb = new StringBuffer();

    for (FieldError error : result.getFieldErrors()) {
        // sb.append(error.getField() + " : " + error.getDefaultMessage() + "\n");
        sb.append(error.getDefaultMessage() + "\n");
    }

    return sb.toString();
}
三叔

You just consider why in your application scenario. A framework is more about considering what is most reasonable most of the time.

Most validations of client data should not be considered "abnormalities", but errors that users are allowed to make without knowing it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template