Spring MVC和Thymeleaf自定义错误消息类型转换

时间:2016-07-24 13:31:59

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

我有一个实体如下:

@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

2 个答案:

答案 0 :(得分:0)

尝试这样做:

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

application.properties

答案 1 :(得分:0)

如果在转换失败的情况下查看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