簡體   English   中英

在 Spring MVC 中使用 @Valid 和 BindingResult 進行驗證無效

[英]Validation with @Valid and BindingResult in Spring MVC isn't working

我有一個表格,您可以使用該表格注冊一個事件/將其保存到數據庫中,我不希望這些字段為空。 如果它們為空,則應顯示一條消息,並且不應將事件保存到數據庫中。

為了處理這個,在 EventController class 上有這個方法:

@PostMapping(value = "/registerEvent")
public String form(@Valid Event event,
                   BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        redirectAttributes.addFlashAttribute("message",
                "Couldn't register this event. Check all fields and try again.");
        return "redirect:/registerEvent";
    }

    eventRepository.save(event);
    redirectAttributes.addFlashAttribute("message",
            "Event successfully registered!");

    return "redirect:/registerEvent";
}

這就是事件 class 的樣子:

//imports

@Entity
public class Event implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotEmpty
    private String name;

    @NotEmpty
    private String venue;

    @NotNull
    private LocalDate date;

    @NotNull
    private LocalTime time;


//other attributes and any methods

對於它的價值,這是 registerEvent html 頁面:

<div class="row container">
    <p>Name: <span th:text="${event.name}"></span></p>
    <p>Venue: <span th:text="${event.venue}"></span></p>
    <p>Date: <span th:text="${event.date}"></span></p>
    <p>Time: <span th:text="${event.time}"></span></p>

    <h5 style="text-align: center;">You can sign up for "<span th:text="${event.name}"></span>" by filling the form below:</h5>
    <form method="post">
        Name: <input type="text" value="" name="name" id="name">
        Rg: <input type="text" value="" name="rg" id="rg">
        <button class="btn waves-effect waves-light" type="submit" name="action">Sign up
            <i class="material-icons right">send</i>
        </button>
    </form>

    <th:block th:include="validationMessage"></th:block>

<!--etc.-->

其中調用validationMessage.html頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Validation message</title>
</head>
<body>
<div class="alert alert-success alert-dismissible" role="alert" th:if="${not #strings.isEmpty(message)}">
    <h5 th:text="${message}" style="color: blue;"></h5>
</div>
</body>
</html>

但是,如果我將字段留空並以這種方式提交,看起來“空”事件不會觸發 bindingResult.hasNoErrors() 並且仍然會保存到數據庫中 — 日期和時間為 NULL,名稱和地點為空.

在這種情況下,我希望消息“無法注冊事件......”,但無論如何我總是得到“事件成功注冊”。

我究竟做錯了什么?

我認為您缺少redirectAttributes.addAttribute(attributeName, attributeValue); ,你可以嘗試添加它們嗎?

redirectAttributes.addAttribute("name", event.getName()); , ETC...

您可以在此處找到更多信息。

此外,在大多數情況下,您不應將實體用作DTO 我建議您首先創建一個您調用的服務,在其中您將DTO map 到一個實體,然后調用您的eventRepository來保存該實體。 有關DTO pattern更多信息,以及有關控制器服務存儲庫體系結構的信息,請參見此處

暫無
暫無

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

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