首页 > 解决方案 > thymeleaf 和 spring boot 应用程序中未显示表单验证错误

问题描述

我正在研究 spring boot 和 thymeleaf,我面临一个问题,即在 thymeleaf html 验证错误中没有出现我已经尝试了所有堆栈溢出但没有结果。

这是控制器:

@Controller
public class LoginRegistrationController {
        @PostMapping("/register")
    public String register(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model,
            RedirectAttributes redirectAttributes) {

        boolean isExist = userService.isUserExist(user.getEmail());

        if (isExist) {
                   // here I will include code later
        }
        if (bindingResult.hasErrors()) {
            model.addAttribute("user", user);
            redirectAttributes.addFlashAttribute("message", "Registration Failed");
            redirectAttributes.addFlashAttribute("alertClass", "alert-danger");
            return "redirect:/registerUserPage";
        }

        return "redirect:/registerUserPage";
    }

}

用户实体:

@Entity
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userId;

    @NotNull
    @NotBlank(message = "Please Enter First Name")
    private String firstName;

    private String middleName;

    @NotNull
    @NotBlank(message = "Please Enter Last Name")
    private String lastName;

    @NotNull
    @NotBlank(message = "Please Enter Email")
    @Pattern(regexp = Constants.emailPattern, message = "Please Enter correct Email. Eg. \"someone@example.com\"")
    private String email;

    @NotNull
    @NotBlank(message = "Please Enter Primary Phone number")
    private String primaryPhone;

    private String secondaryPhone;

    @NotNull
    @NotBlank(message = "Please Enter Password")
    private String Password;

    @ManyToOne(targetEntity = UserRole.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @NotNull
    @NotEmpty(message = "Please select Role")
    private List<UserRole> roleId = new ArrayList<UserRole>();
//getters and setters
}

用户角色实体:

@Entity
@Table(name = "User_Role")
public class UserRole {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int roleId;

    @NotNull
    @NotBlank
    private String roleName;
//getters and setters

}

HTML 表单部分:

                    <form th:action="@{/register}" th:method="post" th:object="${user}">
                        <input class="w3Text" type="text" placeholder="First Name" name="firstName" id="firstName"
                            th:field="*{firstName}" />
                        <span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"
                            class="alert alert-danger"></span>
                        <input class="w3Text" type="text" placeholder="Middle Name" name="middleName" id="middleName"
                            th:field="*{middleName}" />
                        <input class="w3Text" type="text" placeholder="Last Name" name="lastName" id="lastName"
                            th:field="*{lastName}" />
                        <span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}"
                            class="alert alert-danger"></span>
                        <input class="email" type="email" placeholder="Email" name="email" id="email"
                            th:field="*{email}" />
                        <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="alert alert-danger"></span>
                        <input class="w3Text" type="text" placeholder="Primary Phone No." name="primaryPhone"
                            id="primaryPhone" th:field="*{primaryPhone}" />
                        <span th:if="${#fields.hasErrors('primaryPhone')}" th:errors="*{primaryPhone}"
                            class="alert alert-danger"></span>
                        <input class="w3Text" type="text" placeholder="Secondary Phone No." name="secondaryPhone"
                            id="secondaryPhone" th:field="*{secondaryPhone}" />
                        <input class="" type="password" placeholder="Password" name="password" id="password"
                            th:field="*{password}" />
                        <span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"
                            class="alert alert-danger"></span>
                        <select th:field="*{roleId}" class="optionUserRole w3Text" name="userRole" id="userRole">
                            <option class="roleSelect" value="">Select One Option</option>
                            <option class="roleSelect" th:each="userRole :${userRoles}" th:value="${userRole.roleId}"
                                th:text="${userRole.roleName}"></option>
                        </select>
                        <span th:if="${#fields.hasErrors('roleId')}" th:errors="*{roleId}" class="alert alert-danger"></span>
                        <input type="submit" value="Register" />
                    </form>

如果我将必填字段设置为空白但未出现字段,则预期结果将出现在下面。我在浏览器中检查过,但输入标签下方没有跨度标签。

标签: javaspring-bootjpathymeleaf

解决方案


将您设置重定向属性的部分替换为以下代码。

    if (bindingResult.hasErrors()) {
        //model.addAttribute("user", user); 
        redirectAttributes.addFlashAttribute("user", user);
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.user", bindingResult);
        redirectAttributes.addFlashAttribute("message", "Registration Failed");
        redirectAttributes.addFlashAttribute("alertClass", "alert-danger");
        return "redirect:/registerUserPage";
    }

推荐阅读