Spring mvc 如何对Spring MVC中数据转换失败的消息进行个性化设置?
我有一个Spring MVC web应用程序,如下所示:Spring mvc 如何对Spring MVC中数据转换失败的消息进行个性化设置?,spring-mvc,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 erro
@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
}
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控制器验证用户时,如果未指定此参数,它会告诉用户“颜色是必需的”。此消息显示在web表单中。但是,如果字符串“BLUE”被传递给color(这不是3个枚举选项之一),我会收到如下消息:
@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
}
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表单中
正如这条消息所指出的,它与验证器没有任何关系;此消息是在运行验证程序之前创建的。Spring尝试将字符串“BLUE”转换为枚举,因此失败并生成此消息
那么,我如何让Spring MVC对这条消息进行个性化处理呢?
我想说的不是“未能将java.lang.String类型的属性值转换为…”,而是简单的“无效颜色”。您可以在相同的
.properties
文件中定义这些消息,您可以在这些文件中为Spring MVC国际化/本地化定义消息(您也可以对它们进行本地化)。它同时适用于:验证(JSR-303)和数据绑定(数据转换)错误
描述了消息的格式
解释如何配置资源包(您只需用英语定义消息)。实施国际化需要进一步的配置。请参阅教程中的外部化和国际化部分。您是否尝试过在消息属性文件中添加类似于
typeMismatch.java.lang.Integer=必需的整数?