JSR 303验证相关问题及解决 办法
2017-01-04 本文已影响137人
GuaKin_Huang
使用 Hibernate Validator
导入Hibernate Validator
的相关jar
包

在相关字段属性上进行注解
@Size(min = 2, max = 6, message = "{Size.product.name}")
message 可以不写,会使用默认的来自JSR 303验证器的错误消息;
如果要自定义错误消息的话,请看自定义错误消息操作步骤;
- Product类
public class Product {
private int id;
@Size(min = 2, max = 6)
private String name;
private float price;
private Date date;
public Product() {
}
// 、、、getter and setter
}
- ProductController类
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private IProductService productService;
@RequestMapping("/input")
public String inputInfo(Model model) {
model.addAttribute("product", new Product());
return "product-add";
}
//必须用@Valid 对Product参数进行标注
@RequestMapping("/add")
public String addProduct(@Valid @ModelAttribute Product product, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError:allErrors){
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
return "product-add";
}
productService.add(product);
return "redirect:/product/list";
}
// 、、、、其他操作
}
效果:

以上操作就可以实现验证器验证了,不过错误消息来自JSR 303
的默认错误提示消息;
下面是自定义错误提示消息的操作:
先在Resource
添加属性文件,
其中
ValidationMessages
即 properties的名称,注意:properties文件的名字一定要命名成:ValidationMessages.properties
填入相关错误提示信息:
格式:
constraint.object.property
为了覆盖以@Size
标注约束的 Product 对象的 name 属性,可以在属性文件中使用下面的键:
Size.product.name
为了覆盖以@Past
标注约束的 Product 对象的 date 属性,可以在属性文件中使用下面的键:
Past.product.date
内容如下:

- 验证器不需要显式注册,但是如果想要从某个属性文件中获取错误消息,则需要通过声明
messageSource bean
,高速Spring
要去查找这个文件;
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="ValidationMessages"/>
</bean>
- 在Product更改如下
public class Product {
private int id;
@Size(min = 2, max = 6, message = "{Size.product.name}")
private String name;
private float price;
private Date date;
public Product() {
}
// 、、、getter and setter
}
效果:

解决中文乱码问题
- IntelliJ IDEA 2016设置

- Eclipse设置
