gpt4 book ai didi

java - Hibernate Validator 不起作用,但我不知道为什么

转载 作者:行者123 更新时间:2023-12-02 11:04:34 28 4
gpt4 key购买 nike

我在模型类上添加了一些约束注释:

public class Items {
private Integer id;

@Size(min=1,max=30,message="${items.name.length.error}")
private String name;

private Float price;

@NotNull(message="${items.createTime.isNUll}")
private Date createTime;

// setters and getter
}

public class ItemsCustom extends Items {

// add some new details

}

我还设置了配置 XML 文件:

<mvc:annotation-driven
conversion-service="conversionService" validator="validator"></mvc:annotation-driven>

<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>

这是 CustomValidationMessages.properties:

items.name.length.error=the length of name must be more than 1 character and less than 30 characters 
items.createTime.isNUll=the create time must be not null

这是 Controller :

@RequestMapping(value="/submitItems",method=RequestMethod.POST)
public ModelAndView submitItems(@Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{

List<ObjectError> errors = bindingResult.getAllErrors();
if(bindingResult.hasErrors()) {
System.out.println();
for(ObjectError e : errors) {
System.out.println(e.getDefaultMessage());
}
}

ModelAndView mav = new ModelAndView();
// some process...
return mav;
}

我认为一切都准备好了,但行不通!有人帮忙吗?

最佳答案

将 Controller 内的注释@Validated更改为@Valid

import javax.validation.Valid;

关于java - Hibernate Validator 不起作用,但我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51075349/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com