プロジェクトを作成します
アイデアを使用して、スプリングブートプロジェクトを作成し、Web、検証、およびFreemarkerを選択します。
最初に効果をチェックしてください
エンティティクラスを作成します
注釈を作成して追加します。コードは次のとおりです
パブリッククラスの人は、Serializable {@notnull @length(min = 3、max = 10)//ユーザー名の長さは3〜10のプライベート文字列ユーザー名です。 @notnull @min(18)//最年少は18歳の私的整数年齢です。 @notnull // Regultityを使用してフィールドを確認します。メッセージ:検証障害の情報を設定します@pattern(regexp = "[//w-//.] +@///.)+ [az] {2,3}、メッセージ="メッセージ= "メールボックス形式は不正です")private文字列メール; public string getemail(){return email; } public void setemail(string email){this.email = email; } public string getUsername(){return username; } public void setUsername(string username){this.username = username; } public Integer getage(){return age; } public void Setage(整数年齢){this.age = age; }}コントローラーを構成します
コード:
@controllerpublic class webcontroller extends webmvcconfigureradapter {@override public void addViewControllers(ViewControllerRegistryレジストリ){//ルートを追加し、addviewcontroller( "/results")。 } @getMapping( "/")public string showform(person person){return "form"; } @PostMapping("/") public String checkPersonInfo(@Valid Person person, BindingResult bindingResult, RedirectAttributes redirectAttributes) { // Use BindingResult to verify the correctness of form data if (bindingResult.hasErrors()) { // Return the submitted form content to the page intact and display it redirectattributes.addflashattribute( "person"、person); 「フォーム」を返します。 } "redirect:/results"を返します。 }}注:@validアノテーションを忘れないでください
フォームページ
Springタグは、フォームページで使用され、検証に失敗したデータを取得します。 Spring-BootでSpringタグを使用する場合は、spring.ftlファイルをリソースに配置してから、application.ymlに次の構成を追加できます。
spring.ftlファイルパス: org.springframework.web.servlet.view.freemarker.spring.ftl
春:FreeMarker:設定:auto_import:/spring.ftl as Spring
フォームページコード
<form action = "/" method = ""> <div> <label for = "username"> username </label> <@spring.bind "person.username"/> <input type = "text" id = "username" name = "username" value = "$ {person.username!}" placeholder = "placehordors" <div> <label for = "age"> age </label> <@spring.bind "person.age"/> <input type = "number" name = "age" value = "$ {person.age!}" placeholder = "age"/> <span> <@spring.showerrors "" "/>> </span </div> <div> <@sprind <@spring> < "person.email"/> <入力タイプ= "テキスト" id = "email" name "name =" email "value =" $ {person.email!} "placeholder =" email "/> <span> <@spring.showerrors" "/> </span> </div> <入力タイプ=" submit "/>> </>>>注:最初に<@spring.bind "person.username"/>を使用してフィールドをバインドする必要があります。次に<@spring.showErrors ""/>を使用してエラーメッセージを取得する必要があります
参照してください
https://spring.io/guides/gs/validating-form-input/
要約します
上記は、フォーム検証の冬眠バリダーターがSpringブートに追加され、FreeMarkerテンプレートにエラーメッセージが表示されることを紹介した編集者です(推奨)。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!