如何为Spring MVC中的数据转换失败个性化消息?

Dav*_*lla 4 spring-mvc

我有一个Spring MVC Web应用程序如下:

@Controller
@RequestMapping("/users")
public class UserController extends FrontEndController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("user") User user, Errors errors, Model model) {
        ...
    }
}

class User {
    @NotBlank(message = "user name is mandatory")
    String userName;

    public enum Color {RED, GREEN, YELLO}

    @NotNull(message = "color is mandatory)
    private Color color;
    // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

当我的Web控制器验证用户时,如果未指定此参数,则告知"颜色是必需的".此消息显示在Web表单中.但是,如果字符串"BLUE"传递给颜色(这不是3个枚举选项之一),我会收到如下消息:

Failed to convert property value of type java.lang.String to required type User$Color for property color; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull User$Color for value BLUE; nested exception is java.lang.IllegalArgumentException: No enum constant User.Color.BLUE.
Run Code Online (Sandbox Code Playgroud)

此消息显示在Web表单中.

正如hibernate验证器枚举How to personality错误信息所指出的那样此消息与验证器无关; 在验证程序运行之前创建此消息.Spring尝试将字符串"BLUE"转换为枚举,因此它失败并生成此消息.

那么,我怎么能告诉Spring MVC个性化这个消息呢?而不是"无法将类型java.lang.String的属性值转换为...",我想说一些简单的"无效颜色".

Ale*_*xey 6

您可以在.properties为Spring MVC国际化/本地化定义消息的相同文件中定义这些消息(您也可以对它们进行本地化).它适用于:验证(JSR-303)和数据绑定(数据转换)错误.

这里描述了消息的格式.

此问题解释了如何配置资源包(这是您用英语定义消息所需的全部内容).实施国际化将需要进一步配置.请参阅教程中的"外化和国际化"部分.