---
title: "Spring MVC中修改校验的异常信息"
author: "JetMah"
date: "2010-11-24T22:04:54Z"
tags: []
categories: ["企业架构"]
slug: "spring-mvc"
draft: false
lastmod: "2010-11-24T22:04:54Z"
id: 821887
url: "https://jetma.iteye.com/blog/821887"
---

原文出处: [Spring MVC中修改校验的异常信息](http://www.javatang.com/archives/2010/11/23/5817513.html)  
作者: Jet Mah from [Java堂](http://www.javatang.com/)  
声明: **可以非商业性任意转载, 转载时请务必以超链接形式标明文章原始出处、作者信息及此声明！**

 

使用一个例子来说明一下，Spring使用的是3.0.x：

01. public class Account {
02. @ Pattern ( regexp = " \[a-z0-9]{3,50} " )
03. private   String name ;
04. @ NotNull
05. @ NumberFormat ( style = Style . CURRENCY )
06. private   BigDecimal balance = new BigDecimal ( " 1000 " ) ;
07. @ DateTimeFormat ( style = " S- " )
08. @ Future
09. private   Date renewalDate = new Date ( new Date () . getTime () + 31536000000 L ) ;
10. // 省略 getter & setter...
11. }

 

接下来使用注解创建一个Controller：

01. @ Controller
02. @ RequestMapping ( value = " /account " )
03. public   class AccountController {
04. /\**
05. \* 如果view采用JSP的话&lt;code&gt;@ModelAttribute&lt;/code&gt;注解可以省略，但是如果是使用Velocity或FreeMarker
06. \* 的话必须要加上，而且&lt;code&gt;@Valid&lt;/code&gt;注解和后面的BindingResult类型的参数之间不能有其他参数。
07. \*/
08. @ RequestMapping ( method = RequestMethod . POST )
09. public   String create ( @ Valid @ ModelAttribute ( " account " ) Account account , BindingResult result ) {
10. if   ( result . hasErrors ()) {
11. return   " account/createForm " ;
12. }
13. // ...
14. return   " redirect:/account/ " + account . getId () ;
15. }
16. }

另外还有一个view文件、配置文件等等，具体的可以查看[Spring MVC Basic Sample](https://src.springframework.org/svn/spring-samples/mvc-basic/trunk/) 。

 

OK，接下来说重点。我参考上面的Spring MVC Basic Sample中的做法也做了一个类似的表单，在表单中的balance中输入非数字的时候旁边的错误信息会出现下面的异常信息：

> Failed to convert property value of type java.lang.String to required type java.math.BigDecimal for property balance; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value “eff” from type java.lang.String to type java.math.BigDecimal; nested exception is java.lang.IllegalArgumentException: Unable to parse eff

 

这个就很郁闷了，明显是格式转换出错，但是列出来一堆的异常信息，对用户来说非常不友好。于是开始在Google中搜索也没有找到比较好的说法，后 来运行了Spring MVC Basic Sample，不显示上面的异常信息，而只是显示一句话：”could not be parsed“，这个效果正是我们所期待的。于是我将例子中的所有spring配置文件、Bean信息、Controller都做了对比，甚至JSP模板 都一样，但是一到我自己的项目中就会出现那个异常，当时非常郁闷。

 

后来无意中在Google中查到到了参考资料中的一篇帖子，里面提到只要在messages.properties文件中设置 typeMismatch属性就可以了，于是我猛然想到Spring MVC Basic Sample中也有个messages.properties文件，打开之后赫然看到果然有一条typeMismatch属性：

1. typeMismatch=could not be parsed

 

原来是在这里设置的，真的很郁闷。还好，参考资料中的帖子中还提到可以设置具体的类型，比如可以这样设置：

1. \## 全局的配置信息
2. typeMismatch=输入的数据格式不正确
3. \## 针对BigDecimal类型的错误信息
4. typeMismatch.java.math.BigDecimal=请输入数字
5. \## 针对Date类型的错误信息
6. typeMismatch.java.util.Date=请在{0}中输入正确的日期

 

参考资料：  
[Spring MVC Data Binding and user-friendly error messages](http://www.velocityreviews.com/forums/t302365-spring-mvc-data-binding-and-user-friendly-error-messages.html)