使用 Spring 3 验证向导页面 [英] Validating wizard pages with Spring 3
问题描述
我开始研究如何在 Spring 中为类似向导的表单创建控制器,并遇到了 AbstractWizardFormController,我很快注意到它已被弃用.
I started researching how to create a controller for a wizard-like form in Spring and came across the AbstractWizardFormController, which I quickly noticed was deprecated.
然后我进一步挖掘并发现了如何用 Spring 3 完成类似的事情.这个例子虽然没有做任何类型的验证(例如通过 @Valid
),所以我想知道如何验证向导的每一步?
I then dug a bit further and found how to accomplish something similar with Spring 3. This example does not do any sort of validation though (e.g. via @Valid
), so I'm wondering how does one validate each step of a wizard?
是否有可能每个步骤都有自己的支持 Form 对象,然后使用 @SessionAttributes
来存储它们的值,以便在调用最终提交时(大概在表单的最后一页)?
Would it be possible for each step have its own backing Form object and then use @SessionAttributes
to store their values for when a final submit is called (presumably on the last page of the form)?
感谢您的帮助.
(PS:不需要 WebFlow 的解决方案是理想的.)
(P.S.: Solutions that don't require WebFlow would be ideal.)
推荐答案
我不知道有什么方法可以使用 @Valid 注释解决这个问题,但是您应该能够利用 JSR-303 验证来实现做到这一点.作为一个有点人为的例子:
I don't know of a way to pull this off with the @Valid annotation, but you should be able to take advantage of the JSR-303 validation to accomplish this. As a somewhat contrived example:
public class User {
@NotNull(message = "First name can't be blank", groups = {Step1.class, FinalStep.class})
private String firstName;
@NotNull(message = "Last name can't be blank", groups = {Step1.class, FinalStep.class})
private String lastName;
@NotNull(message = "Email can't be blank", groups = {Step1.class, FinalStep.class})
private String emailAddress;
@NotNull(message = "Please provide a valid address", groups = {Step2.class, FinalStep.class})
private Address address;
// getters/setters...
public interface Step1 {}
public interface Step2 {}
public interface FinalStep {}
}
您可以利用 JSR-303 支持验证组这一事实,通过提供标记接口来表示您的向导步骤.
You can take advantage of the fact that JSR-303 supports validation groups by providing marker interfaces to represent your wizard steps.
然后,不要依赖@Valid 注解,而是将 Validator 实例注入您的控制器并调用:
Then, instead of relying on the @Valid annotation, inject a Validator instance into your controller and call:
validator.validate(user, /*<step interface>.class*/);
在您的 processPage 方法中(在您链接的问题中引用 Controller),然后
in your processPage method (referencing Controller in your linked question), and then
validator.validate(user, FinalStep.class);
在您的 processFinish 调用中.
in your processFinish call.
这篇关于使用 Spring 3 验证向导页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!