1

簡単な質問をしてすみません。たくさん検索しましたが、正確な解決策が見つかりません。

私の春のBeanクラスには、(private int id)のようなintフィールドがあります。注釈を使用@NotEmptyしました。

入力フィールドにアルファベットや文字列ではなく、数字のみを許可する必要があります。使用する必要のある注釈。

@NumberFormat(style = Style.NUMBER)@Digits(fraction = 0, integer = 5)注釈を試しましたが、何もうまくいきませんでした。

フォーム検証の解決策または例を教えてください...

4

1 に答える 1

0

参考文献の関連部分を注意深く読むことをお勧めします。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>
于 2013-01-18T11:32:17.690 に答える