【问题标题】:Spring MVC and Thymeleaf custom error message type conversionSpring MVC 和 Thymeleaf 自定义错误消息类型转换
【发布时间】:2026-01-30 21:40:01
【问题描述】:

我有一个实体如下:

@Entity
public class MyEntity {

    @Column(name = "id")
    @Id @GeneratedValue
    private Long id;
    private int SiteId;
   //...getters & setters etc..
}

@Controller 中的一个方法:

@RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(@Valid @ModelAttribute("myEntity") MyEntity myEntity, BindingResult result) {

        if (result.hasErrors()) { 
            return "edit"; 
        } 
        myEntityRepository.save(myEntity);
        return "redirect:/home"; 
    }

在我的 edit.html 文件中:

<form name="form"  th:action="@{/edit}" th:object="${myEntity}" method="post">
    <div class="form-group col-sm-3">
        <label class="control-label" for="siteId">Site ID</label>
        <input class="form-control" type="text" th:field="*{siteId}"/>
        <p th:if="${#fields.hasErrors('siteId')}" 
        class="label label-danger" th:errors="*{siteId}">My custom error message</p>
    </div>
    <div class="form-group">
        <input type="submit" value="Confirme" class="btn btn-primary" />
    </div>
</form>

我的 siteId 字段下显示此消息:Failed to convert property value of type [java.lang.String] to required type [int] for property sectorId; nested exception is java.lang.NumberFormatException: For input string: "random string" 而不是我要显示的消息,即My custom error message

【问题讨论】:

    标签: java validation spring-mvc spring-boot thymeleaf


    【解决方案1】:

    如果您在转换失败的情况下查看您的BindingResult result,您会看到:

    BindingResult.errors[0].codes = [
        0 = "typeMismatch.myEntity.sectorId"
        1 = "typeMismatch.sectorId"
        2 = "typeMismatch.int"
        3 = "typeMismatch"
    ]
    

    也就是说,如果您想更改错误消息,您需要转到带有消息的本地化文件(例如messages.properties)并在那里设置错误消息:

    typeMismatch.myEntity.sectorId = Sector must be a number
    

    或一般用于任何int

    typeMismatch.int = Must be a number
    

    有关 Spring MVC 中消息本地化的更多信息,请参阅https://www.baeldung.com/spring-custom-validation-message-source

    【讨论】:

      【解决方案2】:

      尝试添加这个:

      typeMismatch.classNameWrittenLikeThat.fieldName = custom text to show as error
      

      致您的messages.properties

      【讨论】:

      • messages.properties(或您配置为消息包的任何内容),而不是 application.properties