在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
}
当我的Web控制器验证User时,如果未指定此参数,它将告诉“颜色是强制性的”。此消息显示在Web表单中。但是,如果将字符串“
BLUE”传递给color(这不是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.
此消息显示在Web表单中。
正如如何为hibernate验证器枚举添加个性错误消息所指出的那样?此消息与验证程序无关;此消息是在运行验证程序之前创建的。Spring尝试将字符串“BLUE”转换为枚举,因此它失败并生成此消息。
那么,如何告诉Spring MVC个性化此消息?而不是“无法将类型java.lang.String的属性值转换为…”,我想说一些简单的“无效颜色”。
问题答案: