我正在尝试使用getAttributes()在两个验证器bean中获取两个页面属性,但是该函数无法获得它们的结果NullPointerException。使用来自另一个页面和另一个验证器的完全相同的代码,我没有遇到任何问题。我在Windows XP 32位上使用JSF 2.2和Apache 7。
不起作用的代码:
addEmployee.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:o="http://omnifaces.org/ui">
<h:body>
<ui:composition template="template.xhtml">
<ui:define name="title">
#{msg.addEmployee}
</ui:define>
<ui:define name="body">
<script type="text/javascript">
PrimeFaces.locales['el'] = {
closeText: 'Κλείσιμο',
prevText: 'Προηγούμενο',
nextText: 'Επόμενο',
monthNames: ['Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάϊος', 'Ιούνιος', 'Ιούλιος', 'Άυγουστος', 'Σεπτέμβιος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος'],
monthNamesShort: ['Ιαν', 'Φεβ', 'Μαρ', 'Απρ', 'Μαι', 'Ιουν', 'Ιουλ', 'Αυγ', 'Σεπ', 'Οκτ', 'Νοε', 'Δεκ'],
dayNames: ['Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο'],
dayNamesShort: ['Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ'],
dayNamesMin: ['Κ', 'Δ', 'Τρ', 'Τε', 'Πε', 'Πα', 'Σ'],
weekHeader: 'Εβδ',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: '',
timeOnlyTitle: 'Επιλογή Ώρας',
timeText: 'Χρόνος',
hourText: 'Ώρα',
minuteText: 'Λεπτό',
secondText: 'Δεύτερολεπτο',
currentText: 'Τώρα',
ampm: false,
month: 'Μήνας',
week: 'Εβδομάδα',
day: 'Μέρα',
allDayText: 'Όλη Μέρα'
};
</script>
<h:form id="addEmployeePanel" prependId="false">
<p:growl id="messages" showDetail="true" life="10000"/>
<table align="center" boarder="0">
<tr align="center">
<td align="center">
<p:outputPanel>
<p:panel id="basicInfoPanel">
<f:facet name="header">
#{msg.basicInfo}
</f:facet>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="surnameInput" value="#{msg.surname}:" />
<p:inputText value="#{addEmployee.surname}" id="surnameInput" required="true" label="surname" requiredMessage="#{msg.surnameRequired}" maxlength="128" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ωa-zA-Z\s]*$" message="#{msg.regexSurnameError}" />
</p:inputText>
<h:outputLabel for="nameInput" value="#{msg.name}:" />
<p:inputText value="#{addEmployee.name}" id="nameInput" required="true" label="name" requiredMessage="#{msg.nameRequired}" maxlength="128" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ωa-zA-Z\s]*$" message="#{msg.regexΝameError}" />
</p:inputText>
<h:outputLabel for="fathersNameInput" value="#{msg.fathersName}:" />
<p:inputText value="#{addEmployee.fathersName}" id="fathersNameInput" required="true" label="fathersName" requiredMessage="#{msg.fathersNameRequired}" maxlength="128" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ωa-zA-Z\s]*$" message="#{msg.regexFathersΝameError}" />
</p:inputText>
<h:outputLabel for="mothersNameInput" value="#{msg.mothersName}:" />
<p:inputText value="#{addEmployee.mothersName}" id="mothersNameInput" required="true" label="mothersName" requiredMessage="#{msg.mothersNameRequired}" maxlength="128" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ωa-zA-Z\s]*$" message="#{msg.regexMothersΝameError}" />
</p:inputText>
<h:outputLabel for="birthDateCalendar" value="#{msg.birthDate}:" />
<p:calendar value="#{addEmployee.surname}" id="birthDateCalendar" required="true" label="birthDate" requiredMessage="#{msg.birthDateRequired}" validatorMessage="#{msg.regexBirthDateError}" showOn="button" locale="el" size="32">
</p:calendar>
<h:outputLabel for="identityNumberInput" value="#{msg.identityNumber}:" />
<p:inputText value="#{addEmployee.identityNumber}" id="identityNumberInput" required="true" label="identityNumber" requiredMessage="#{msg.identityNumber}" maxlength="12" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ω0-9\s]*$" message="#{msg.regexIdentityNumberError}" />
</p:inputText>
<h:outputLabel for="afmShortInput" value="#{msg.afmShort}:" />
<p:inputText value="#{addEmployee.afm}" id="afmShortInput" required="true" label="afmShortInput" requiredMessage="#{msg.afmShortRequired}" maxlength="9" size="32">
<f:validator validatorId="afmValidator" />
<f:attribute name="afm" value="#{afmShortInput}"/>
</p:inputText>
<h:outputLabel for="amkaShortInput" value="#{msg.amkaShort}:" />
<p:inputText value="#{addEmployee.amka}" id="amkaShortInput" required="true" label="amkaShortInput" requiredMessage="#{msg.amkaShortRequired}" maxlength="128" size="32">
<f:validator validatorId="amkaValidator" />
<f:attribute name="amka" value="#{amkaShortInput}"/>
</p:inputText>
<h:outputLabel for="attributeMenu" value="#{msg.attribute}:" />
<p:selectOneMenu id="attributeMenu" value="#{addEmployee.selectedAttribute}" required="true" requiredMessage="#{msg.attributeRequired}" style="width:305px">
<f:selectItem itemLabel="#{msg.select}" itemValue=""/>
<f:selectItems value="#{addEmployee.attribute}"/>
<p:ajax update="containerPanel, infoOutputPanel, extraInfoPanel, rankMenu, educationTypeMenu" listener="#{addEmployee.updateAttributeSelected}" />
</p:selectOneMenu>
</h:panelGrid>
</p:panel>
<p:blockUI block="basicInfoPanel" trigger="add">
<p:graphicImage value="/images/ajax_loader.gif" height="64" width="64"/>
</p:blockUI>
</p:outputPanel>
</td>
</tr>
<tr align="center">
<td align="center">
<h:panelGroup id="containerPanel" layout="block">
<p:outputPanel id="infoOutputPanel" rendered="#{addEmployee.infoOutputPanelRendered}" autoUpdate="true">
<p:effect type="slide" event="load"/>
<p:panel id="extraInfoPanel">
<f:facet name="header">
#{msg.extraInfo}
</f:facet>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="idInput" value="#{msg.id}:"/>
<p:inputText value="#{addEmployee.id}" id="idInput" required="true" label="id" requiredMessage="#{msg.idRequired}" maxlength="32" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[α-ωΑ-Ωa-zA-Z0-9\s]*$" message="#{msg.regexIdError}" />
</p:inputText>
<h:outputLabel for="rankMenu" value="#{msg.rank}:"/>
<p:selectOneMenu id="rankMenu" value="#{addEmployee.selectedRank}" required="true" requiredMessage="#{msg.rankRequired}" style="width:305px">
<f:selectItem itemLabel="#{msg.select}" itemValue=""/>
<f:selectItems value="#{addEmployee.rank}"/>
</p:selectOneMenu>
<h:outputLabel for="socialSecurityMenu" value="#{msg.socialSecurity}:"/>
<p:selectOneMenu id="socialSecurityMenu" value="#{addEmployee.selectedSocialSecurity}" required="true" requiredMessage="#{msg.socialSecurityRequired}" style="width:305px">
<f:selectItem itemLabel="#{msg.select}" itemValue=""/>
<f:selectItems value="#{addEmployee.socialSecurity}"/>
</p:selectOneMenu>
<h:outputLabel for="educationTypeMenu" value="#{msg.educationType}:"/>
<p:selectOneMenu id="educationTypeMenu" value="#{addEmployee.selectedDegree}" required="true" requiredMessage="#{msg.educationTypeRequired}" style="width:305px" disabled="#{addEmployee.degreeDisabled}">
<f:selectItem itemLabel="#{msg.select}" itemValue=""/>
<f:selectItems value="#{addEmployee.degree}"/>
</p:selectOneMenu>
<h:outputLabel for="ibanInput" value="#{msg.iban}:"/>
<p:inputText value="#{addEmployee.iban}" id="ibanInput" required="true" label="iban" requiredMessage="#{msg.ibanRequired}" maxlength="27" size="32">
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[GR]{2}[0-9]{25}$" message="#{msg.regexIbanError}" />
</p:inputText>
<f:facet name="footer">
<p:commandButton id="add" value="#{msg.add}" update="messages" action="#{loginMgmtBean.login}"/>
</f:facet>
</h:panelGrid>
</p:panel>
<p:blockUI block="extraInfoPanel" trigger="add">
<p:graphicImage value="/images/ajax_loader.gif" height="64" width="64"/>
</p:blockUI>
</p:outputPanel>
</h:panelGroup>
</td>
</tr>
</table>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
AfmValidator
package extra.validators;
import extra.dao.DBConnection;
import extra.logger.DBLogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import static org.omnifaces.util.Faces.getRemoteAddr;
import org.primefaces.context.RequestContext;
@FacesValidator("afmValidator")
public class AfmValidator implements Validator {
//Η αποδεκτή μορφή (χαρακτήρες) για το όνομα χρήστη
private static final String AFM_PATTERN = "(^[0-9]{9})$";
private Pattern pattern;
private Matcher matcher;
public AfmValidator() {
pattern = Pattern.compile(AFM_PATTERN);
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
con = DBConnection.getInstance().openConnection();
//Φόρτωση του ΑΦΜ από την σελίδα που τον κάλεσε
UIInput uiInputAfm = (UIInput) component.getAttributes().get("afm");
String afm = uiInputAfm.getSubmittedValue().toString();
if (con != null) {
try {
//Έλεγχος για το αν το ΑΦΜ είναι σωστό
matcher = pattern.matcher(afm);
if (!matcher.matches()) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Αποτυχία προσθήκης", "Ο Α.Φ.Μ. μπορεί να αποτελείται μόνο από αριθμούς"));
} else {
//Έλεγχος για τον αν υπάρχει ήδη ο εργαζόμενος
String select = "SELECT VAL FROM EMP WHERE VAL = ? AND PARAM_CD = 'AFM'";
pst = con.prepareStatement(select);
pst.setString(1, afm);
rs = pst.executeQuery();
if (rs.next()) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Αποτυχία προσθήκης", "Ο εργαζόμενος υπάρχει ήδη"));
}
}
} catch (SQLException ex) {
DBLogger.addLog(afm, getRemoteAddr(), "AfmValidator.validate", "trying to validate afm", ex.toString());
ex.printStackTrace();
RequestContext errorContext = RequestContext.getCurrentInstance();
errorContext.addCallbackParam("added", false);
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Αποτυχία προσθήκης", "Προέκυψε σφάλμα κατά την προσπάθεια προσθήκης νέου εργαζόμενου. Αν το πρόβλημα εμφανιστεί ξανά, παρακαλώ επικοινωνήστε με τον διαχειριστή του συστήματος"));
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
con.close();
} catch (SQLException ex) {
DBLogger.addLog(afm, getRemoteAddr(), "AfmValidator.validate", "trying to close the resultset/preparedstatement/connection", ex.toString());
ex.printStackTrace();
}
}
} else {
DBLogger.addLog(afm, getRemoteAddr(), "AfmValidator.validate", "could not open the connection");
RequestContext errorContext = RequestContext.getCurrentInstance();
errorContext.addCallbackParam("added", false);
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Αποτυχία προσθήκης", "Προέκυψε σφάλμα κατά την προσπάθεια προσθήκης νέου εργαζόμενου. Αν το πρόβλημα εμφανιστεί ξανά, παρακαλώ επικοινωνήστε με τον διαχειριστή του συστήματος"));
}
}
}
错误:
com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: java.lang.ClassCastException: java.lang.String cannot be cast to javax.faces.component.UIInput
at army.olkes.extra.validators.AfmValidator.validate(AfmValidator.java:40)
at javax.faces.component.UIInput.validateValue(UIInput.java:1165)
at javax.faces.component.UIInput.validate(UIInput.java:983)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
at org.primefaces.component.panel.Panel.processValidators(Panel.java:281)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:322)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:184)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:155)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
答案 0 :(得分:0)
相关观点代码:
<h:outputLabel for="afmShortInput" value="#{msg.afmShort}:" />
<p:inputText value="#{addEmployee.afm}"
id="afmShortInput"
required="true"
label="afmShortInput"
requiredMessage="#{msg.afmShortRequired}"
maxlength="9"
size="32">
<f:validator validatorId="afmValidator" />
<f:attribute name="afm" value="#{afmShortInput}"/>
</p:inputText>
验证码:
UIInput uiInputAfm = (UIInput) component.getAttributes().get("afm");
表达式#{afmShortInput}
将无法解析为 UIInput 实例,因为单个UI树元素不会自动绑定到任何范围。可以将组件注入范围,但将控件绑定到其自己的属性之一似乎是不明智的。您已经在验证程序中引用了该组件。使用:
UIInput uiInputAfm = (UIInput) component;
答案 1 :(得分:0)
我终于发现我忘记了inputText的“绑定”属性,因此它变成了:
<h:outputLabel for="afmShortInput" value="#{msg.afmShort}:" />
<p:inputText value="#{addEmployee.afm}"
id="afmShortInput"
required="true"
label="afmShortInput"
requiredMessage="#{msg.afmShortRequired}"
binding="#{afm}"
maxlength="9"
size="32">
<f:validator validatorId="afmValidator" />
<f:attribute name="afm" value="#{afm}"/>
</p:inputText>