【问题标题】:Validation error while filling up the form填写表格时出现验证错误
【发布时间】:2016-10-20 10:08:56
【问题描述】:

当输入错误时,我正在尝试设置验证自定义错误。

这是我在百里香模板的帮助下编写的表格:

<form th:action="@{/addPet}" th:object="${petDto}" method="post">
            <table>
                <tr>
                    <td>Pet name:</td>
                    <td><input type="text" th:field="*{pet.petName}" /></td>
                    <td th:if="${#fields.hasErrors('pet.petName')}" th:errors="*{pet.petName}">fieldError</td>
                </tr>
                <tr>
                    <td>Owner First name:</td>
                    <td><input type="text" th:field="*{owner.firstName}" /></td>
                    <td th:if="${#fields.hasErrors('owner.firstName')}" th:errors="*{owner.firstName}">fieldError</td>
                </tr>
                <tr>
                    <td>Owner Last name:</td>
                    <td><input type="text" th:field="*{owner.lastName}" /></td>
                    <td th:if="${#fields.hasErrors('owner.lastName')}" th:errors="*{owner.lastName">fieldError</td>
                </tr>
                <tr>
                    <td>Owner Number:</td>
                    <td><input type="text" th:field="*{owner.phoneNumber}" /></td>
                    <td th:if="${#fields.hasErrors('owner.phoneNumber')}" th:errors="*{owner.phoneNumber}">fieldError</td>
                </tr>
                <tr>
                    <td><input type="submit" value="add" /></td>
                </tr>
            </table>

所以传递的 dto 包含两个字段:

public class PetDto {


    private Pet pet;
    private Owner owner;

现在当我输入错误时,我得到了这个:

here was an unexpected error (type=Internal Server Error, status=500).
Validation failed for classes [pl.kaczynski.model.Owner] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Length must be between 2 and 15 characters.', propertyPath=lastName, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{Size}'} ConstraintViolationImpl{interpolatedMessage='Length must be between 2 and 15 characters.', propertyPath=firstName, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{Size}'} ConstraintViolationImpl{interpolatedMessage='numeric value out of bounds (<9 digits>.<0 digits> expected)', propertyPath=phoneNumber, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{javax.validation.constraints.Digits.message}'} ]

我的目标是必须在同一视图中的输入字段旁边显示错误消息,而不是重定向到错误页面。我为对象 Pet 和 Owner 制作了类似的表单页面,并且工作正常,这让我认为我的组合类 DTO 存在问题。

编辑// 这是模型类:

@Entity
public class Pet extends BaseClass{

    @Column(name = "pet_name")
    @Size(min=2,max=15,message="{Size}")
    private String petName;
    @OneToOne()
    @JoinColumn(name = "owner_Id")
    private Owner owner;

@Entity
public class Owner extends BaseClass {

    @Column(name = "first_name")
    @Size(min = 2, max = 15, message = "{Size}")
    private String firstName;

    @Column(name = "last_name")
    @Size(min = 2, max = 15, message = "{Size}")
    private String lastName;

    @Column(name = "phone")
    @Digits(fraction = 0, integer = 9)
    private String phoneNumber;

这里是控制器:

@RequestMapping(value = "/addPet", method = RequestMethod.POST)
    public String addPetPost(@Valid @ModelAttribute(value="petDto") PetDto petDto, BindingResult result){

        if(result.hasErrors())
            return "/addPet";

        Owner owner = petDto.getOwner();
        Pet pet = petDto.getPet();
        pet.setOwner(owner);

        ownerService.add(owner);
        petService.add(pet);
        return "redirect:addPet";
    }

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

    试试这个方法:

    <tr>
        <td>Pet name:</td>
        <td><input type="text" th:field="*{pet.petName}" /></td>
        <span th:if="${#fields.hasErrors('pet.petName')}">
            <ul>
                <li th:each="err : ${#fields.errors('pet.firstName')}" th:text="${err}">error text</li>
            <ul>
        </span>
    </tr>
    

    如果您对同一字段有多个错误消息(例如 First Name is requiredFirst Name must have 2 to 15 characters 等),它们将打印在列表。

    【讨论】:

    • 这不起作用,我认为问题可能出在 BindingResult 结果对象上,因为我对其进行了调试,并且 if(result.hasErrors()) 不正确,并且流程更进一步,因此spring boot 中出现 whitelabel 页面错误。所以现在的目标是让结果看到错误
    • 你想要什么?
    • 我认为你的错误在这里if(result.hasErrors()) return "/addPet";。您必须返回相同的表单,例如 return "petForm"; 或您的命名方式。
    • 代码无法到达那里,所以基本上它不管那里有什么,因此工作流程会跳过它
    猜你喜欢
    • 1970-01-01
    • 2016-08-08
    • 2021-05-10
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多