简体   繁体   English

Java JSF关于自定义验证

[英]Java JSF About Custom Validation

i am using this way in custom validation i am little bit confused if this way is correct or not if i assumed that i have this form: 我在自定义验证中使用这种方式,如果这种方式正确与否,如果我假设我具有这种形式,我会有点困惑:

<h:form id="myForm>
 <h:outputText value="user name" />
 <h:inputText value="#userBean.userName" id="userName" />

 <h:outputText value="Password" />
 <h:inputText value="#userBean.Password" id="passwd" />
</h:form>

and i have its Managed Bean : 我有它的Managed Bean:

@ManagedBean(name="userBean")
@SessionScoped
public class UserBeanData{
   private String userName;
   private String password;
   // with setters and getters........
   //
}

and the custom validator to validate the Managed Bean field and the Implmentation like : 以及用于验证Managed Bean字段和Implationation的自定义验证器,例如:

@Override
public validate(FacesContext context, UIComponent component, Object value) throws ValidatorException{
Map<String, String> params = context.getExternalContext().getRequestParametersMap();

String username = params.get("myForm:username");
String pass = params.get("myForm:passwd");

// validate : if fields are not null check if the user exists if the result is empty , throws a validation Message Error
}

My Question is : Retrieving the Managed bean values like this is true or not ???? 我的问题是:像这样检索托管bean的值是否正确?

You're basically looking for the solution in the wrong direction. 基本上,您正在寻找错误方向的解决方案。 Validation is only applicable on the individual submitted values, eg minimum/maximum length, non-empty/null, regex pattern, etcetera. 验证仅适用于单个提交的值,例如最小/最大长度,非空/空值,正则表达式模式等。 But you want to invoke a business action based on all submitted values: logging-in an user. 但是您要基于所有提交的值来调用业务操作:登录用户。 This is not exactly input validation. 这不完全是输入验证。

Just add required="true" to the both input components and perform the job in the action method. 只需将required="true"添加到两个输入组件中,然后以action方法执行作业即可。

Eg 例如

<h:form id="myForm>
    <h:outputText value="user name" />
    <h:inputText value="#{userBean.userName}" id="userName" />
    <h:message for="userName" />

    <h:outputText value="Password" />
    <h:inputSecret value="#{userBean.password}" id="passwd" />
    <h:message for="passwd" />

    <h:commandButton value="Login" action="#{userBean.login}" />
    <h:messages globalOnly="true" />
</h:form>

with

@ManagedBean
@RequestScoped
public class UserBean {

    private String userName;
    private String password;

    @EJB
    private UserService service;

    public String login() {
        User user = service.find(userName, password);

        if (user != null) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap("user", user);
            return "home?faces-redirect=true";
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Unknown login"));
            return null;
        }
    }

    // ...
}

Pay attention to the validate method's firm. 注意validate方法的牢固性。 It has an UIComponent parameter that is the component validated by the method. 它具有UIComponent参数,该参数是通过方法验证的组件。 This UIComponent has both the current value ( getValue() ) and the value that the user submitted ( getSubmittedValue() ). UIComponent同时具有当前值( getValue() )和用户提交的值( getSubmittedValue() )。

You might have to cast that UIComponent to the particular type of component you're validating (int this case, it's an UIInput ). 您可能必须将UIComponent转换为要验证的特定类型的组件(在这种情况下,这是UIInput )。

Now, if you're going to validate both username and password prior to a log in, there are several ways to do it. 现在,如果您要在登录之前同时验证用户名和密码,则有几种方法可以执行此操作。 In your case, validating the username field with the password field as an added parameter should suffice. 在您的情况下,用密码字段作为添加参数验证用户名字段就足够了。 You can achieve that by doing this: 您可以通过执行以下操作来实现:

<h:outputText value="user name" />
<h:inputText value="#userBean.userName" id="userName" validator="#{yourBean.validateLogin}">
    <f:attribute name="pass" value="#{passwordField}" />
</h:inputText>

<h:outputText value="Password" />
<h:inputText value="#userBean.Password" id="passwd" binding="#{passwordField}"/>

Note that the binding in the password <h:inputText/> is related to the value of the pass of the <f:attribute/> tag nested in your username <h:inputText/> . 请注意,密码<h:inputText/>中的binding与嵌套在username <h:inputText/>中的<f:attribute/>标记的pass值有关。 With this setup, you can perform your validation like this: 使用此设置,您可以像这样执行验证:

public void validateLogin(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    //I suppose it's a typo, but your validate method lacks the return type.
    String username = (String) value;
    UIInput passwordInput = component.getAttributes().containsKey("pass") ? 
        (UIInput) component.getAttributes().get("pass") : null;
    if(passwordInput != null) {
        //Just to be sure the input was added as a parameter successfuly
        String submittedPassword = passwordInput.getSubmittedValue();
        //Now, do your validations based on the strings "username"
        //and "password".
    }
}

Since all of this is being done in the validation phase, the values aren't set in your managed bean yet, that's why you have to play around a little with the submitted values. 由于所有这些操作都是在验证阶段完成的,因此尚未在托管bean中设置这些值,这就是为什么您必须稍微处理提交的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM