Spring MVC:绑定模型属性时防止异常

Spring MVC : Preventing Exceptions when binding model attribute

在我的模型中,我使用长整型等数字数据类型。 当我形成 post 个,但提供字符串时,它会输出异常堆栈跟踪,包括 NumberFormatException。 我怎样才能正确包装它以便 UI 看不到异常堆栈跟踪?

您需要在控制器中 命令参数(带有 @Value 注释)之后 有一个 BindingResult 参数。然后您可以检查 bindingResult 并决定如何处理无法绑定的内容。

当你有那个 BindingResult 参数时,控制器方法就会被调用,即使有绑定错误,你也必须自己处理错误。

通常它看起来有点像这个例子(创建用户或再次呈现用户创建页面):

@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid UserCreateCommand userCreateCommand,
                           BindingResult bindingResult) {
   if (bindingResult.hasErrors()) {
        //or some of your handling for bindingResult errors
        return new ModelAndView("user/create", userCreateCommand", userCreateCommand);
    } else {
    ...
    }
}

But how do I differentiate the normal validation errors vs. validation errors occuring due to NumberFormatException ?

BindingResult有几种获取FieldErrors的方法,例如BindingResult.getFieldErrors()FieldError 有 属性 boolean isBindingFailure()

如果要显示该异常的自定义消息,您应该配置 Spring 以使用 message.properties 文件并指定 'typeMismatch.className.propertyName' 消息或类型不匹配的全局消息。

例如(Spring 3.2): 在servlet-config.xml

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="classpath:messages/messages">
</bean>

在src/main/resources/messages/messages.properties

typeMismatch = Invalid data format!

在控制器中:

public String addObject(@Valid @ModelAttribute("objectForm")
ObjectForm objectForm, BindingResult result, Model model)
{
        if (result.hasErrors())
        {
            return "/addObject";
        }
    //...
}

在jsp中:

<form:errors path="propertyName" cssClass="divErrorsServer" element="div" />

您还可以使用:

System.out.println(result.getAllErrors());

查看您可以在消息文件中为该错误添加哪些代码。例如,当我在 private Double weight 字段上使用 String 时,我得到了这些代码:

[typeMismatch.objectForm.weight,
typeMismatch.weight,
typeMismatch.java.lang.Double,
typeMismatch]