JSF 2.0验证控制器 [英] JSF 2.0 validation controller
问题描述
我对JSF/Java非常陌生,但是我想知道是否有人知道创建自定义验证控制器的好方法.我的Web应用程序中有很多表格,其中的字段重叠,例如名字,SSN或电子邮件.我想创建一个控制器来处理所有这些验证和消息.
I am very new to JSF/Java but I wanted to know if anyone knows a good way to create a custom validation controller. I have a lot of forms in my web application with fields that overlap such as First Name, SSN, or email. I wanted to create a Controller that would handle all of these validations and messages.
这是个好主意吗?我一直在网上查看文档,但似乎每个示例都发现他们将验证方法放在特定的bean中,而不是在控制器中.
Is this a good idea? I have been looking online on documentation but it looks like every example I have found they put the validation method within a specific bean and not in a controller.
任何示例/指向示例/建议的链接都可以很好地实现这种效果.
Any examples / links to examples / advice on a good way of implementing something like this would be great.
我正在使用JSF 2.0
I am using JSF 2.0
推荐答案
这不是正常的方法.您应该将控制任务委托给FacesServlet
.它的工作做得非常好.如果您想要的只是从托管Bean分离验证,那么只需创建一个独立的类即可实现 @FacesValidator
注释.
This is not the normal approach. You should delegate the controlling task to the FacesServlet
. It's doing its job perfectly fine. If all what you want is decoupling validation from the managed bean, then just create a standalone class which implements javax.faces.validator.Validator
. To get it to loaded automagically, just mark it with the appropriate @FacesValidator
annotation.
这是一个开球示例:
package com.example;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator(value="ssnValidator")
public class SSNValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// Implement as you did originally in the bean method.
}
}
您可以将其声明为 <f:validator>
在任何UIInput
组件中,如下所示:
You can declare it as <f:validator>
in any UIInput
component as follows:
<h:inputText value="#{bean.ssn}">
<f:validator validatorId="ssnValidator" />
</h:inputText>
这篇关于JSF 2.0验证控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!