java - thymeleaf 和 spring boot 应用程序中未显示表单验证错误

标签 java spring-boot jpa thymeleaf

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

这是 Controller :

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

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

最佳答案

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

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

关于java - thymeleaf 和 spring boot 应用程序中未显示表单验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56994895/

相关文章:

java - 是否可以为接口(interface)类型创建对象

java - 配置spring缓存咖啡因

sql - 并发插入实体集合

java - 将 JPA Spring boot 与 SQL Server 结合使用

java - 如何从 JPA 唯一约束违规中获取值?

java - 如何在RxJava中传输多个参数

Java 耦合 - 我应该跨不同模块依赖服务层还是存储库层?

java - 是否可以使用 JavaMail API 获取特定邮件的电子邮件服务提供商

spring - 在 Spring 测试中忽略 MongoDB 套接字连接

java - 在 Spring boot 中使用 JPA 生成的序列 id(来自数据库序列)由其他服务器/实例共享,并导致违反唯一约束