3

spring-mvc-showcase サンプル プロジェクト ( spring-mvc-showcase github ) を分析しています。間違った日付形式 (スクリーンショットの生年月日フィールド) にヒットしたときに JSP ページに検証応答が表示される方法に混乱しています。これらの ConversionFailedException の詳細なしで、カスタム メッセージを使用してユーザー フレンドリーにするにはどうすればよいですか?

スクリーンショット:

ここに画像の説明を入力

アノテーション主導の検証が適用されます。以下は、birthDate フィールドを表す Bean クラスのコード セグメントです。

FormBean.java

@DateTimeFormat(iso=ISO.DATE)
@Past
private Date birthDate;

フォーム送信を担当するメソッド:

FormController.java

@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@Valid FormBean formBean, BindingResult result, 
                            @ModelAttribute("ajaxRequest") boolean ajaxRequest, 
                            Model model, RedirectAttributes redirectAttrs) {
    if (result.hasErrors()) {
        return null;
    }
    // Typically you would save to a db and clear the "form" attribute from the session 
    // via SessionStatus.setCompleted(). For the demo we leave it in the session.
    String message = "Form submitted successfully.  Bound " + formBean;
    // Success response handling
    if (ajaxRequest) {
        // prepare model for rendering success message in this request
        model.addAttribute("message", message);
        return null;
    } else {
        // store a success message for rendering on the next request after redirect
        // redirect back to the form to render the success message along with newly bound values
        redirectAttrs.addFlashAttribute("message", message);
        return "redirect:/form";            
    }
}
4

2 に答える 2

9

ここでバインディング エラーを処理していることに注意してください。これらは、実際の JSR-303 検証が実行されるずっと前にスローされ、失敗したフィールドの JSR-303 制約違反をオーバーライドします。

バインディング エラーのコードはtypeMismatch. したがって、たとえばこれをメッセージ プロパティに追加できます。

typeMismatch.birthDate = Invalid birth date format.

JavaDoc でDefaultMessageCodesResolverDefaultBindingErrorProcessorをチェックして、Spring のエラー コード解決がどのように機能するかを確認してください。

于 2013-09-30T11:00:10.133 に答える