8
respostas

Curso Java e JSF I Sua aplicação web com JSF2 - Erro ao tentar gravar autor.

Bom dia, alguém poderia ajudar, está ocorrendo o erro a seguir quando tento gravar o autor:

ADVERTÊNCIA: #{autorBean.gravar}: java.lang.ExceptionInInitializerError javax.faces.FacesException: #{autorBean.gravar}: java.lang.ExceptionInInitializerError at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:117) at javax.faces.component.UICommand.broadcast(UICommand.java:315) at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:791) at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1256) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:407) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Unknown Source) Caused by: javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101) ... 29 more

8 respostas

Boa tarde Carlos, este erro pode ser tanto no arquivo xhtml como no arquivo java, vc poderia postar o código dos 2 arquivos no fórum?

Bom dia, Tiago, segue os códigos:

autor.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">

Novo Autor

Dados do Autor

AutorBeanjava package br.com.caelum.livraria.bean;

import javax.faces.bean.ManagedBean;

import br.com.caelum.livraria.dao.DAO; import br.com.caelum.livraria.modelo.Autor;

@ManagedBean public class AutorBean {

private Autor autor = new Autor();

public Autor getAutor() { return autor; }

public void gravar() { System.out.println("Gravando autor " + this.autor.getNome());

new DAO(Autor.class).adiciona(this.autor); } }

Autor.java package br.com.caelum.livraria.modelo;

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;

@Entity public class Autor {

@Id @GeneratedValue private Integer id; private String nome;

public String getNome() { return nome; }

public void setNome(String nome) { this.nome = nome; }

public Integer getId() { return id; }

public void setId(Integer id) { this.id = id; }

}

Boa tarde Carlos, o código do arquivo autor.xhtml ficou truncado no fórum, pra que possa te auxiliar clique em "inserir código" e coloque o código no local indicado:

ele vai ficar desse jeito

De qualquer maneira vou postar o código aqui que tenho desse projeto e está funcionando:

autor.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://java.sun.com/jsf/html">

<h:body>
    <h1>Novo Autor</h1>
    <h:form>
        <fieldset>
            <legend>Dados do Autor</legend>
            <h:panelGrid columns="2">
                <h:outputLabel value="Nome:" for="nome" />
                <h:inputText id="nome" value="#{autorBean.autor.nome}" />
                <h:commandButton value="Gravar" action="#{autorBean.gravar}" />
            </h:panelGrid>
        </fieldset>
    </h:form>
</h:body>

</html>

AutorBean

package br.com.caelum.livraria.bean;

import javax.faces.bean.ManagedBean;

import br.com.caelum.livraria.dao.DAO;
import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.util.RedirectView;

@ManagedBean
public class AutorBean {

    private Autor autor = new Autor();

    public Autor getAutor() {
        return autor;
    }

    public RedirectView gravar() {
        System.out.println("Gravando autor " + this.autor.getNome());
        new DAO<Autor>(Autor.class).adiciona(this.autor);
        this.autor = new Autor();

        return new RedirectView("livro");
    }
}

Boa tarde, Tiago, segue o código:

<?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://java.sun.com/jsf/html">

    <h:body>
        <h1>Novo Autor</h1>
        <h:form>
            <fieldset>
                <legend>Dados do Autor</legend>
                <h:panelGrid columns="2">
                    <h:outputLabel value="Nome:" for="nome" />
                    <h:inputHidden value="#{autorBean.autor.id}"/>
                    <h:inputText id="nome" value="#{autorBean.autor.nome}" />
                    <h:commandButton value="Gravar" action="#{autorBean.gravar}" />
                </h:panelGrid>
            </fieldset>
        </h:form>
    </h:body>

</html>

Colei o seu código no meu projeto e não houve erro, estou suspeitando que seja algum problema em relação ao banco de dados, o erro parece muito com esse relatado aqui: https://cursos.alura.com.br/forum/topico-java-lang-exceptionininitializererror-29692

Vc conseguiria postar a stacktrace completa do erro?

Bom dia, Tiago

O Servidor Start sem erros, o problema ocorre quando chamo no navegador "http://localhost:8080/livraria/autor.xhtml" e peço para gravar o nome do autor. Substituir no persistence.xml de org.hibernate.ejb.HibernatePersistence para org.hibernate.jpa.HibernatePersistenceProvider, mas continua o mesmo erro. Segue o erro que aparece no navegado ao tentar gravar o auto:

HTTP Status 500 – Internal Server Error
Type Exception Report

Message java.lang.IncompatibleClassChangeError: class org.hibernate.ejb.HibernatePersistence has interface org.hibernate.ejb.AvailableSettings as super class

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

HTTP Status 500 – Internal Server Error
Type Exception Report

Message java.lang.IncompatibleClassChangeError: class org.hibernate.ejb.HibernatePersistence has interface org.hibernate.ejb.AvailableSettings as super class

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: java.lang.IncompatibleClassChangeError: class org.hibernate.ejb.HibernatePersistence has interface org.hibernate.ejb.AvailableSettings as super class
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

javax.faces.el.EvaluationException: java.lang.IncompatibleClassChangeError: class org.hibernate.ejb.HibernatePersistence has interface org.hibernate.ejb.AvailableSettings as super class
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:791)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1256)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

Continuação do erro:

java.lang.IncompatibleClassChangeError: class org.hibernate.ejb.HibernatePersistence has interface org.hibernate.ejb.AvailableSettings as super class
    java.base/java.lang.ClassLoader.defineClass1(Native Method)
    java.base/java.lang.ClassLoader.defineClass(Unknown Source)
    java.base/java.security.SecureClassLoader.defineClass(Unknown Source)
    org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2320)
    org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:816)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1261)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1121)
    javax.persistence.spi.PersistenceProviderResolverHolder$PersistenceProviderResolverPerClassLoader$CachingPersistenceProviderResolver.loadResolverClasses(PersistenceProviderResolverHolder.java:142)
    javax.persistence.spi.PersistenceProviderResolverHolder$PersistenceProviderResolverPerClassLoader$CachingPersistenceProviderResolver.<init>(PersistenceProviderResolverHolder.java:122)
    javax.persistence.spi.PersistenceProviderResolverHolder$PersistenceProviderResolverPerClassLoader.getPersistenceProviders(PersistenceProviderResolverHolder.java:80)
    javax.persistence.Persistence.getProviders(Persistence.java:69)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:53)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    br.com.caelum.livraria.dao.JPAUtil.<clinit>(JPAUtil.java:10)
    br.com.caelum.livraria.dao.DAO.adiciona(DAO.java:19)
    br.com.caelum.livraria.bean.AutorBean.gravar(AutorBean.java:20)
    java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.base/java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:791)
    javax.faces.component.UIViewRoot.