各位大神好,请教个问题
1.环境
spring 4.3.7
hibernate-validator-5.4.1
2.配置如下
<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和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);
}
……
}
问题:
为什么一定要在代码中用result.hasErrors()显示判断?
难道不能验证UserRequest中的字段不符合定义就直接抛异常,这样不更合理些吗?
问题:
为什么一定要在代码中用result.hasErrors()显示判断?
难道不能验证UserRequest中的字段不符合定义就直接抛异常,这样不更合理些吗?
例如我们在参数异常的时候返回给前端的是异常的具体参数名和描述,不是 Spring 给出的所有异常信息,如果 Spring 自动抛出异常,那么返回的信息你自己就不好控制了。