Spring:如何解决验证错误 - >错误代码 - >错误信息 [英] Spring: How to resolve a validation error -> error code -> error message

查看:104
本文介绍了Spring:如何解决验证错误 - >错误代码 - >错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring中,验证后我们在控制器中得到一个 BindingResult 对象。

In Spring, after validation we get a BindingResult object in the controller.

很简单,如果我收到验证错误,我想重新显示我的表单,并在每个受影响的字段上方显示错误消息。

Simple enough, if I get validation errors I want to re-display my form with the error message above each afflicted field.

所以要检查字段用户名的字段错误我的 FormObject 我打电话:

So to check for field errors on field username of my FormObject I call:

FieldError usernameFieldError = bindingResult.getFieldError("username");

很好,现在我持有 FieldError 对象假设我使用 DefaultMessageCodeResolver 现在包含4个可能的错误代码。

Great, now I hold a FieldError object which, assuming I'm using the DefaultMessageCodeResolver now contains something like 4 possible error codes.

如何从 FieldError - >一个可供用户使用的字符串?

How do I go from FieldError -> A string that is consumable to the user?

我有在我的webapplication上下文中定义了 MessageSource ,因此我可以将单个错误代码映射到消息。

I have a MessageSource defined in my webapplication context, so I can map a single error code to a message.

但有时候默认消息是最好的,有时我希望其中两个错误代码可能有相关的消息,所以我们需要选择最好的消息。

But sometimes the default message will be best, and sometimes I expect that two of the error codes might have a relevant message, so we need to choose the best one.

我可以使用哪种方法来确定为字段错误提供的最佳可能的错误消息?

What method do I use to determine the best possible error message to present for a field error?


  • 我是否需要编写一些算法来检查所有错误代码并从最具体的选择中选择?

  • spring是否提供任何支持帮助确定最具体的错误信息?

  • 整个过程看起来如此漫长而令人费解,我认为春天应该让这些东西变得简单。也许我完全偏离了基地?

推荐答案

正如你猜测的那样,你正在制作它比你需要的更难自己。 FieldError 对象本身是 MessageSourceResolvable 。您无需从中获取代码,然后手动将单个代码移至消息源并继续查看。您只需将其传递给 MessageSource ,它就会找到在您的语言环境中定义了翻译的最具体的一个。 (假设你的代码解析器以正确的顺序放置它们。)

You are, as you guessed, making it way harder on yourself than it needs to be. The FieldError object is itself a MessageSourceResolvable. You don't need to get the codes off of it then take individual codes manually to your message source and go looking. You can just pass it to your MessageSource and it will find the most specific one that has a translation defined in your locale. (assuming your code resolver put them on in the right order.)

在大多数情况下你甚至都不需要这样做。通常不需要在您的支持对象上放置错误并自行翻译它们。 jsp库中的表单命名空间提供了一个标记,可以为您查找错误消息。您需要做的就是将错误放在 ModelMap 中。请参阅文档:

You really don't even need to do that in most cases though. Putting the Errors on your backing object and translating them yourself isn't usually needed. The form namespace in the jsp library provides a tag that looks up error messages for you. All you need to do is put the Errors in the ModelMap. See docs:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp -formtaglib-errorstag

这篇关于Spring:如何解决验证错误 - >错误代码 - >错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆