问题表单验证的Spring注释?

时间:2013-01-18 08:59:31

标签: java spring javabeans spring-annotations

很抱歉问这个简单的问题。我搜索了很多,但找不到确切的解决方案。

在我的spring bean类中,我有int字段(private int id)。我使用了@NotEmpty注释。

我只需要在输入字段中只允许数字而不是任何字母或字符串。我需要使用什么注释。

我已尝试过@NumberFormat(style = Style.NUMBER)@Digits(fraction = 0, integer = 5)注释,但没有任何效果。

请向我推荐表格验证的解决方案或任何示例......

1 个答案:

答案 0 :(得分:0)

我建议你仔细阅读relevant part of the reference。 您可以创建实现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) { ... }

或'global':

<?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>
相关问题