在thymeleaf和Spring Boot应用程序中未显示表单验证错误

时间:2019-07-11 17:53:24

标签: java spring-boot jpa thymeleaf

我正在研究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
}

UserRole实体:

@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>

如果我将必填字段设置为空白但未出现字段,则预期结果将是以下所有内容。我已经在浏览器中进行了检查,但输入标签下方没有span标签。

1 个答案:

答案 0 :(得分:0)

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

    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";
    }