我有一个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的属性值转换为...",我想说一些简单的"无效颜色".
归档时间: |
|
查看次数: |
2300 次 |
最近记录: |