Spring验证,如何让PropertyEditor生成特定的错误消息 [英] Spring validation, how to have PropertyEditor generate specific error message

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

问题描述

我正在使用Spring进行表单输入和验证。表单控制器的命令包含正在编辑的模型。某些模型的属性是自定义类型。例如,Person的社会安全号码是自定义SSN类型。

I'm using Spring for form input and validation. The form controller's command contains the model that's being edited. Some of the model's attributes are a custom type. For example, Person's social security number is a custom SSN type.

public class Person {
    public String getName() {...}
    public void setName(String name) {...}
    public SSN getSocialSecurtyNumber() {...}
    public void setSocialSecurtyNumber(SSN ssn) {...}
}

并在Spring表单编辑命令中包装Person:

and wrapping Person in a Spring form edit command:

public class EditPersonCommand {
    public Person getPerson() {...}
    public void setPerson(Person person) {...}
}

因为Spring不知道如何将文本转换为SSN ,我使用表单控制器的binder注册客户编辑器:

Since Spring doesn't know how to convert text to a SSN, I register a customer editor with the form controller's binder:

public class EditPersonController extends SimpleFormController {
    protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) {
        super.initBinder(req, binder);
        binder.registerCustomEditor(SSN.class, "person.ssn", new SsnEditor());
    }
}

和SsnEditor只是一个自定义 java.beans.PropertyEditor 可以将文本转换为SSN对象:

and SsnEditor is just a custom java.beans.PropertyEditor that can convert text to a SSN object:

public class SsnEditor extends PropertyEditorSupport {
    public String getAsText() {...} // converts SSN to text
    public void setAsText(String str) {
        // converts text to SSN
        // throws IllegalArgumentException for invalid text
    }
}

如果 setAsText 遇到无效且无法转换为SSN的文本,然后抛出 IllegalArgumentException (每 PropertyEditor setAsText 的规格)。我遇到的问题是文本到对象的转换(通过 PropertyEditor.setAsText())发生之前我的Spring验证器被调用。当 setAsText throws IllegalArgumentException 时,Spring只显示在 errors.properties <中定义的一般错误消息/ code>。我想要的是一个特定的错误消息,取决于输入的SSN无效的确切原因。 PropertyEditor.setAsText()将确定原因。我已尝试在 IllegalArgumentException 的文本中嵌入错误原因文本,但Spring只是将其视为一般错误。

If setAsText encounters text that is invalid and can't be converted to a SSN, then it throws IllegalArgumentException (per PropertyEditor setAsText's specification). The issue I'm having is that the text to object conversion (via PropertyEditor.setAsText()) takes place before my Spring validator is called. When setAsText throws IllegalArgumentException, Spring simply displays the generic error message defined in errors.properties. What I want is a specific error message that depends on the exact reason why the entered SSN is invalid. PropertyEditor.setAsText() would determine the reason. I've tried embedded the error reason text in IllegalArgumentException's text, but Spring just treats it as a generic error.

有解决方法吗?重复一遍,我想要的是 PropertyEditor 生成的特定错误消息,以显示Spring表单上的错误消息。我能想到的唯一选择是将SSN作为文本存储在命令中并在验证器中执行验证。 SSN对象转换的文本将以 onSubmit 的形式进行。这是不太理想的,因为我的表单(和模型)有很多属性,我不想创建和维护一个将每个模型属性作为文本字段的命令。

Is there a solution to this? To repeat, what I want is the specific error message generated by the PropertyEditor to surface to the error message on the Spring form. The only alternative I can think of is to store the SSN as text in the command and perform validation in the validator. The text to SSN object conversion would take place in the form's onSubmit. This is less desirable as my form (and model) has many properties and I don't want to have to create and maintain a command that has each and every model attribute as a text field.

上面只是一个例子,我的实际代码不是Person / SSN,所以没有必要回复为什么不将SSN存储为文本......

The above is just an example, my actual code isn't Person/SSN, so there's no need to reply with "why not store SSN as text..."

推荐答案

您正在尝试在活页夹中进行验证。这不是活页夹的目的。绑定器应该将请求参数绑定到您的后备对象,仅此而已。属性编辑器将字符串转换为对象,反之亦然 - 它不是为了做任何其他事情。

You're trying to do validation in a binder. That's not the binder's purpose. A binder is supposed to bind request parameters to your backing object, nothing more. A property editor converts Strings to objects and vice versa - it is not designed to do anything else.

换句话说,你需要考虑分离关注点 - 你是尝试将功能强制转换为一个对象,除了将字符串转换为对象外,从不打算做任何事情,反之亦然。

In other words, you need to consider separation of concerns - you're trying to shoehorn functionality into an object that was never meant to do anything more than convert a string into an object and vice versa.

您可以考虑将SSN对象分解为可轻松绑定的多个可验证字段(字符串对象,日期等基本对象)。这样,您可以在绑定后使用验证程序来验证SSN是否正确,或者您可以直接设置错误。使用属性编辑器,抛出IllegalArgumentException,Spring将其转换为类型不匹配错误,因为它就是这样 - 字符串与预期的类型不匹配。就是这样。另一方面,验证器可以做到这一点。只要填充了SSN实例,就可以使用spring绑定标记绑定到嵌套字段 - 必须首先使用new()初始化它。例如:

You might consider breaking up your SSN object into multiple, validateable fields that are easily bound (String objects, basic objects like Dates, etc). This way you can use a validator after binding to verify that the SSN is correct, or you can set an error directly. With a property editor, you throw an IllegalArgumentException, Spring converts it to a type mismatch error because that's what it is - the string doesn't match the type that is expected. That's all that it is. A validator, on the other hand, can do this. You can use the spring bind tag to bind to nested fields, as long as the SSN instance is populated - it must be initialized with new() first. For instance:

<spring:bind path="ssn.firstNestedField">...</spring:bind>

但是,如果您确实希望坚持这条路径,请让您的属性编辑器保留错误列表 - 如果要抛出IllegalArgumentException,将其添加到列表中然后抛出IllegalArgumentException(如果需要,捕获并重新抛出)。因为您可以在与绑定相同的线程中构造属性编辑器,所以如果您只是覆盖属性编辑器的默认行为,它将是线程安全的 - 您需要找到它用来进行绑定的钩子,并覆盖它 - 执行相同的属性编辑器您现在正在进行注册(除了使用相同的方法,以便您可以保留对编辑器的引用),然后在绑定结束时,如果您提供公共访问器,则可以通过从编辑器中检索列表来注册错误。检索完列表后,您可以对其进行处理并相应地添加错误。

If you truly want to persist on this path, however, have your property editor keep a list of errors - if it is to throw an IllegalArgumentException, add it to the list and then throw the IllegalArgumentException (catch and rethrow if needed). Because you can construct your property editor in the same thread as the binding, it will be threadsafe if you simply override the property editor default behavior - you need to find the hook it uses to do binding, and override it - do the same property editor registration you're doing now (except in the same method, so that you can keep the reference to your editor) and then at the end of the binding, you can register errors by retrieving the list from your editor if you provide a public accessor. Once the list is retrieved you can process it and add your errors accordingly.

这篇关于Spring验证,如何让PropertyEditor生成特定的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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