[英]Spring annotation for form validation for issue?
很抱歉问这个简单的问题。 我进行了很多搜索,但找不到确切的解决方案。
在我的spring bean类中,我有int字段,例如(private int id)。 我使用了@NotEmpty
注释。
我只需要在输入字段中允许数字而不是任何字母或字符串。 我需要使用什么注释。
我尝试了@NumberFormat(style = Style.NUMBER)
, @Digits(fraction = 0, integer = 5)
@NumberFormat(style = Style.NUMBER)
@Digits(fraction = 0, integer = 5)
批注,但没有任何结果。
请给我建议解决方案或表单验证的任何示例...
我建议您仔细阅读参考资料的相关部分 。 您创建实现Validator接口的验证器:
public class FooValidator implements Validator {
/**
* This Validator validates *just* Foo instances
*/
public boolean supports(Class clazz) {
return Foo.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Foo foo = (Foo) obj;
if (!isNumeric(foo.getFieldThatShouldBeNumeric())
{
e.rejectValue("fieldThatShouldBeNumeric", "notnumeric");
}
}
}
然后将其“本地”注入控制器本身:
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
或“全局”:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.