FrontPage > Spring Web MVCの覚書
Validation †
1. JSR-303対応 †
- サーブレット設定ファイル(servlet-context.xml等)に以下を記述。
<mvc:annotation-driven />
- 対象beanにアノテーションを記述
例)
public class SampleCommand {
@Size(max=5, message="五文字以内で入力してください。")
private String name;
・・・略
- コントローラのハンドリングメソッドで対象の引数に@Validを記述
例)
@RequestMapping(value="/showMessage",method=RequestMethod.POST)
public String showMessage(@Valid SampleCommand command, BindingResult result, Model model) {
if (result.hasErrors()) {
// バインドエラー処理
}
return "sample/sample";
}
- エラー表示方法は「Springタグライブラリ」参照
1.1 アノテーション一覧 †
- @AssertFalse
falseならOK
サポートタイプ:Boolean, boolean
- @AssertTrue
trueならOK
サポートタイプ:Boolean, boolean
- @DecimalMax("最大値")
サポートタイプ:BigDecimal、BigInteger、String
byte, short, int, long, とラッパークラス
- @DecimalMin("最小値")
サポートタイプ:BigDecimal BigInteger String
byte, short, int, long, とラッパークラス
- @Digits(integer = 整数部桁数, fraction = 小数部桁数)
サポートタイプ:BigDecimal BigInteger String
byte, short, int, long, とラッパークラス
- @Past
過去の日付ならOK
サポートタイプ:java.util.Date java.util.Calendar
- @Future
未来の日付ならOK
サポートタイプ:java.util.Date java.util.Calendar
- @Max(最大値)
サポートタイプ:BigDecimal BigInteger
byte, short, int, long, とラッパークラス
- @Min(最小値)
サポートタイプ:BigDecimal BigInteger
byte, short, int, long, とラッパークラス
- @NotNull
タイプがStringの場合、未入力でも空文字がセットされるので、意味が無い。
- Pattern(regexp="正規表現")
正規表現に一致すればOK
サポートタイプ:String
- @Size(min=最小値, max=最大値)
String.length()
Collection.size()
Map.size()
Array.length()
1.2 エラーメッセージ †
- 直接指定
例)
@Size(min=2, max=20, message = "{min}から{max}桁で入力してください。")
private String message;
- VlidationMessages.propertiesのコピー、編集による指定
ライブラリーにある、hibernate-validator-4.1.0.Final.jar内のorg.hibernate.validator.ValidationMessages.propertiesをsrc/main/resourcesにコピーし、
メッセージを編集する。
- VlidationMessages.propertiesを作成し、keyにより指定する。
src/main/resourcesにValidationMessages.propertiesを作成。
例)
validation.error.size={min}から{max}桁で入力してください。
アノテーションで登録したメッセージのkeyを指定する。
例)
@Size(min=2, max=5, message = "{validation.error.size}")
private String message;
2. 独自Validator †
- org.springframework.validation.Validatorを実装したValidatorを作成する。
例)
package org.springframework.samples.mvc.basic.sample;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class SampleCommandValidator implements Validator {
public boolean supports(Class<?> candidate) {
// SampleCommand用Validator
return SampleCommand.class.isAssignableFrom(candidate);
}
public void validate(Object obj, Errors errors) {
// SampleCommand.nameがnullまたは空白の場合エラーとする。
// validation.error.notNullはエラーメッセージを指定するKEY
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "validation.error.notNull");
// 0以下ならエラーとする。
if (command.getNum() < 0) {
errors.rejectValue("num", "validation.error.negativeValue");
}
}
}
- 作成したValidatorをコントローラに指定。
@Controller
public class SampleController {
@InitBinder
void initBinder(WebDataBinder binder) {
binder.setValidator(new SampleCommandValidator());
}
@RequestMapping(value="/showMessage",method=RequestMethod.POST)
public String showMessage(@Valid SampleCommand command, BindingResult result, Model model) {
if (result.hasErrors()) {
// バインドエラー処理
}
return "sample/sample";
}
以下のように記述することでglobalValidatorとして登録されているValidatorをすべてのコントローラーに指定することもできる。
<mvc:annotation-driven validator="globalValidator"/>
- メッセージファイルを指定
サーブレット設定ファイル(servlet-context.xml等)に下記を記述する。
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
- メッセージファイルにエラーメッセージを登録
messages.properties(Localeを使用している場合はmessages_ja.properties)へメッセージを登録
例)
validation.error.notNull=必須です。
validation.error.negativeValue=正の数を入力してください。
フィールドがnameでvalidation.error.notNullを指定した場合、
validation.error.notNull.nameというKeyのメッセージがあればそちらが表示される。
|