簡體   English   中英

Spring 引導 CRUD 應用程序與 Thymeleaf - BindingResult 結果

[英]Spring Boot CRUD Application with Thymeleaf - BindingResult result

我有一個帶有這個 bean 的 SpringBoot 應用程序:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(NON_NULL)
public class UserPayload implements Serializable {

    private Long id;
    @NotEmpty
    private String password;
    @NotEmpty
    private String confirmPassword;
    @NotBlank(message = "Name is mandatory")
    @NotEmpty
    @NotNull
    private String name;
...
}

和 controller:

@PostMapping("/adduser.html")
    public String addUser(@Valid UserPayload userPayload,
                            BindingResult result,
                            Model model,
                            @RequestParam("files") MultipartFile[] multipartFiles) {
...
}

在模板上:

<form action="#" th:action="@{/adduser.html}" th:object="${user}" method="post" enctype="multipart/form-data">


     <input type="text" id="name" class="form-control" th:field="*{name}"  placeholder="Introduce you name">

...

</form>

但是當所有字段為空時,BindingResult 結果顯示 0 錯誤

你的問題可能出於不同的原因。

您可以嘗試的一件事是使用 ModelAttribute 注釋對UserPayload ModelAttribute進行注釋:

@PostMapping("/adduser.html")
public String addUser(@ModelAttribute("userPayload") @Valid UserPayload userPayload,
                      BindingResult result,
                      Model model,
                      @RequestParam("files") MultipartFile[] multipartFiles) {
...
}

也許它可能會有所幫助,因為您似乎還提供了files參數。 請適當調整 model 屬性名稱。

Please, also verify that you have an implementation of the Validation API in your maven dependencies, not only the java.validation API, like hibernate-validator :

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.3.Final</version>
</dependency>

請根據您項目中庫的 rest 設置正確的版本:如果您使用的是 Spring 依賴管理,您可以放心地依賴它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM