[RESOLVIDO] PrimeFaces javax.el.PropertyNotFoundException: Target Unreachable

Pessoal,

Estou com problemas com PrimeFaces 3. Utilizo em uma das minhas páginas uma entidade chamada ClassificadosAutos, que por sua vez se relaciona com ModelosAutos.

Se eu não inicializar estas entidades no ManagedBean o PrimeFaces não consegue renderizar a página lançando a exceção javax.el.PropertyNotFoundException: Target Unreachable.

Mas eu já trabalhei com Struts2 e até mesmo com JSF2 puro e não preciso inicializar as propriedades para que a página seja renderizada. Alguém já passou por isso e sabe uma solução?

Obrigado.

ManagedBean

@Component("autosBean")
@Scope("request")
public class AutosBean extends ClassifiedBean {
	private static final long serialVersionUID = -8427733238096186907L;

	private ClassificadosAutos autos;
...

insert.xml:

...
					<p:selectOneMenu id="model" value="#{autosBean.autos.modeloAutos.id}" required="true" requiredMessage="Model is required">
						<f:selectItem itemLabel="Select..." itemValue="" />
						<f:selectItems value="#{autosBean.models}" var="c" itemLabel="#{c.nome}" itemValue="#{c}"/> 
					</p:selectOneMenu>
...

StackTrace:

SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [] threw exception [javax.el.PropertyNotFoundException: Target Unreachable, 'autos' returned null] with root cause javax.el.PropertyNotFoundException: Target Unreachable, 'autos' returned null at org.apache.el.parser.AstValue.getTarget(AstValue.java:127) at org.apache.el.parser.AstValue.getType(AstValue.java:82) at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:176) at org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.getType(ContextAwareTagValueExpression.java:75) at org.primefaces.renderkit.InputRenderer.getConverter(InputRenderer.java:154) at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeMarkup(SelectOneMenuRenderer.java:49) at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeEnd(SelectOneMenuRenderer.java:41) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:580) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:762) at org.apache.myfaces.shared.renderkit.html.HtmlGridRendererBase.renderChildren(HtmlGridRendererBase.java:349) at org.apache.myfaces.shared.renderkit.html.HtmlGridRendererBase.encodeEnd(HtmlGridRendererBase.java:173) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:580) at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:62) at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:46) at org.primefaces.component.fieldset.FieldsetRenderer.encodeContent(FieldsetRenderer.java:86) at org.primefaces.component.fieldset.FieldsetRenderer.encodeMarkup(FieldsetRenderer.java:68) at org.primefaces.component.fieldset.FieldsetRenderer.encodeEnd(FieldsetRenderer.java:45) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:580) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:762) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:758) at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1900) at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285) at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:115) at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:241) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:199) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) 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:224) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:679)

cara,

vc deve iniciar esse variavel auto, antes de vc entrar nessa pagina.

t+

alissonvia obrigado pela resposta. Mas é justamente isso que eu não quero fazer, iniciar as variáveis dentro do ManagedBean, mas neste intervalo de tempo entre o primeiro post eu consegui implementar uma solução que desta forma você não precisa iniciar nenhuma variável no construtor do ManagedBean ou em outro lugar dentro do próprio ManagedBean.

Segue solução:

  1. Criar uma classe que estende javax.faces.el.PropertyResolver; aqui chamada de PropertyResolverImpl;
  2. Sobre-escrever o método public Object getValue(final Object base, final Object property);
  3. Utilizar Apache Commons BeanUtils para instanciar atributos (variáveis) nulos;
  4. Configurar a nova classe no faces-config.xml: <property-resolver>com.magoit.util.el.PropertyResolverImpl</property-resolver>;

Segue arquivos:

faces-config.xml

        ...
	&lt;application&gt;
		&lt;resource-handler&gt;org.primefaces.application.PrimeResourceHandler&lt;/resource-handler&gt;
		&lt;property-resolver&gt;com.magoit.util.el.PropertyResolverImpl&lt;/property-resolver&gt;
		&lt;variable-resolver&gt;org.springframework.web.jsf.SpringBeanVariableResolver&lt;/variable-resolver&gt;
		&lt;el-resolver&gt;org.springframework.web.jsf.el.WebApplicationContextFacesELResolver&lt;/el-resolver&gt;
	&lt;/application&gt;
        ...

PropertyResolverImpl.java

package com.magoit.util.el;

import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.PropertyNotFoundException;
import javax.faces.el.PropertyResolver;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

@SuppressWarnings(&quot;deprecation&quot;)
public final class PropertyResolverImpl extends PropertyResolver {

	/** Logger available to subclasses */
	protected final Log logger = LogFactory.getLog(getClass());

	@Override
	public Object getValue(final Object base, final Object property) throws EvaluationException, PropertyNotFoundException {
		if (base == null) {
			return null;
		}
		if (property == null) {
			return null;
		}

		Object res = null;
		try {
			Class&lt;?&gt; classType = PropertyUtils.getPropertyType(base, property.toString());
			res = PropertyUtils.getProperty(base, property.toString());
			if (res == null) {
				res = BeanUtils.instantiate(classType);
				PropertyUtils.setProperty(base, property.toString(), res);

				elContext().setPropertyResolved(true);
				return res;
			}
		} catch (Exception e) {
			// do nothing
		}

		elContext().setPropertyResolved(false);
		return null;
	}

	@Override
	public boolean isReadOnly(Object base, int index) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
		return false;
	}

	@Override
	public boolean isReadOnly(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
		return false;
	}

	@Override
	public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
		return null;
	}

	@Override
	public Class&lt;?&gt; getType(Object base, int index) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
		return null;
	}

	@Override
	public Class&lt;?&gt; getType(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
		return null;
	}

	@Override
	public void setValue(Object base, Object property, Object value) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
	}

	@Override
	public void setValue(Object base, int index, Object value) throws EvaluationException, PropertyNotFoundException {
		elContext().setPropertyResolved(false);
	}

	private ELContext elContext() {
		return FacesContext.getCurrentInstance().getELContext();
	}

}

Só uma pergunta, esses outros método sobrescritos não irão influenciar em nada a aplicação ou o comportamento do JSF?

Não jakefrog, pois o JSF2 utiliza um método de sobre-carga de “PropertyResolver”. Se o seu “Resolver” não resolver a propriedade ele passa para o próximo na hierarquia, porem você não pode esquecer de marcar a propriedade elContext().setPropertyResolved(false); .

Abraços,

Marcelo

Não jakefrog, pois o JSF2 utiliza um método de sobre-carga de “PropertyResolver”. Se o seu “Resolver” não resolver a propriedade ele passa para o próximo na hierarquia, porem você não pode esquecer de marcar a propriedade elContext().setPropertyResolved(false); .

Abraços,

Marcelo[/quote]
Valeu pela dica. [=

[quote=marcelolimagomes]alissonvia obrigado pela resposta. Mas é justamente isso que eu não quero fazer, iniciar as variáveis dentro do ManagedBean, mas neste intervalo de tempo entre o primeiro post eu consegui implementar uma solução que desta forma você não precisa iniciar nenhuma variável no construtor do ManagedBean ou em outro lugar dentro do próprio ManagedBean.

Segue solução:

  1. Criar uma classe que estende javax.faces.el.PropertyResolver; aqui chamada de PropertyResolverImpl;
  2. Sobre-escrever o método public Object getValue(final Object base, final Object property);
  3. Utilizar Apache Commons BeanUtils para instanciar atributos (variáveis) nulos;
  4. Configurar a nova classe no faces-config.xml: <property-resolver>com.magoit.util.el.PropertyResolverImpl</property-resolver>;

Segue arquivos:

faces-config.xml

        ...
	&lt;application&gt;
		&lt;resource-handler&gt;org.primefaces.application.PrimeResourceHandler&lt;/resource-handler&gt;
		&lt;property-resolver&gt;com.magoit.util.el.PropertyResolverImpl&lt;/property-resolver&gt;
		&lt;variable-resolver&gt;org.springframework.web.jsf.SpringBeanVariableResolver&lt;/variable-resolver&gt;
		&lt;el-resolver&gt;org.springframework.web.jsf.el.WebApplicationContextFacesELResolver&lt;/el-resolver&gt;
	&lt;/application&gt;
        ...

PropertyResolverImpl.java

[code]
package com.magoit.util.el;

import javax.el.ELContext;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.PropertyNotFoundException;
import javax.faces.el.PropertyResolver;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

@SuppressWarnings("deprecation")
public final class PropertyResolverImpl extends PropertyResolver {

/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());

@Override
public Object getValue(final Object base, final Object property) throws EvaluationException, PropertyNotFoundException {
	if (base == null) {
		return null;
	}
	if (property == null) {
		return null;
	}

	Object res = null;
	try {
		Class&lt;?&gt; classType = PropertyUtils.getPropertyType(base, property.toString());
		res = PropertyUtils.getProperty(base, property.toString());
		if (res == null) {
			res = BeanUtils.instantiate(classType);
			PropertyUtils.setProperty(base, property.toString(), res);

			elContext().setPropertyResolved(true);
			return res;
		}
	} catch (Exception e) {
		// do nothing
	}

	elContext().setPropertyResolved(false);
	return null;
}

@Override
public boolean isReadOnly(Object base, int index) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
	return false;
}

@Override
public boolean isReadOnly(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
	return false;
}

@Override
public Object getValue(Object base, int index) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
	return null;
}

@Override
public Class&lt;?&gt; getType(Object base, int index) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
	return null;
}

@Override
public Class&lt;?&gt; getType(Object base, Object property) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
	return null;
}

@Override
public void setValue(Object base, Object property, Object value) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
}

@Override
public void setValue(Object base, int index, Object value) throws EvaluationException, PropertyNotFoundException {
	elContext().setPropertyResolved(false);
}

private ELContext elContext() {
	return FacesContext.getCurrentInstance().getELContext();
}

}
[/code][/quote]

Obrigado pela a solução ficou otima e me ajudou muito.

marcelolimagomes tem um problema nessa solução, ao utilizar o componente <p:calendar /> a data já está vindo inicializada com a data atual.

sabe uma maneira de corrigir?