【发布时间】:2013-09-10 20:14:00
【问题描述】:
当我在邮政编码中输入内容并点击提交并将国家/地区设置为默认空值时,我得到 javax.faces.FacesException: java.lang.NullPointerException。如果我选择国家,然后输入一切正常的东西。我尝试了 SubmittedValue,但它的工作方式相反 - null 正在工作,然后给出 null 异常。
@FacesValidator("zipV")
public class ZipValidator implements Validator {
LocaleBean Bean = new LocaleBean();
String language;
private static final String ZIP_PATTERN_BG = "\\d{4}";
private static final String ZIP_PATTERN_US = "\\d{5}";
private static final String ZIP_PATTERN_DEFAULT = "[A-Za-z0-9]*";
private String zip_pattern;
private Pattern pattern;
private Matcher matcher;
private String country;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
language = Bean.getLanguage();
UIInput Input = (UIInput) component.getAttributes().get("country");
country = Input.getValue().toString();
String zip = (String) value;
if (country == null || country.isEmpty()) {
return;
}
switch (country) {
case "BGR":
zip_pattern = ZIP_PATTERN_BG;
break;
case "USA":
zip_pattern = ZIP_PATTERN_US;
break;
default:
zip_pattern = ZIP_PATTERN_DEFAULT;
break;
}
pattern = Pattern.compile(zip_pattern);
matcher = pattern.matcher(value.toString());
if (!matcher.matches()) {
switch (language) {
case "en": {
FacesMessage msg = new FacesMessage("Invalid zip.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
case "bg": {
FacesMessage msg = new FacesMessage("Невалиден пощенски код.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
}
}
这是视图:
<h:selectOneMenu id="country" value="#{account.country}" required="true" requiredMessage="#{msg['register.required']}" binding="#{country}">
<f:selectItem itemValue="#{null}" itemLabel="#{msg['register.countryQ']}"/>
<f:selectItems value="#{account.countries}"/>
<f:ajax listener="#{account.loadStates()}" render="state"/>
</h:selectOneMenu>
<h:inputText id="zipcode" required="true" requiredMessage="#{msg['register.required']}" value="#{account.zipcode}">
<f:validator validatorId="zipV"/>
<f:attribute name="country" value="#{country}"/>
</h:inputText>
【问题讨论】:
-
是 Input.getValue().toString() 上的空指针?
-
是的,如果我将其更改为 SubmittedValue,它将使用 null 并且在此之后无法使用。
-
您能解释一下“在此之后”是什么意思吗?你的意思是如果你使用 Input.getSubmittedValue().toString() 那么你没有得到空指针,但是代码在这之后的某个地方不起作用?
-
我在 zip 表单中键入一个值,然后单击提交 - 我没有得到空指针。我更改国家/地区,然后单击提交 - 我得到空指针。
-
getSubmittedValue()不是正确的方法。只有在验证器运行在组件被处理之前,你才应该使用它。这不是这里的情况。验证器在处理完国家/地区组件之后在 zip 组件上运行。
标签: validation jsf jsf-2.2