Configuração JSF

22/05/2009

Boa Tarde , Pessoal estou com dificuldades de configurar o JSF coloquei todos os arquivos na pasta lib do eclipse , mas na hora de rodar o projeto da esse erro: Cannot find FacesContext. Estou no aguardo , obrigado.

Meu arquivo xml :


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>JSF_SHIFT</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
</web-app>
Cristian Mietlicki

Cristian Mietlicki

Curtidas 0

Respostas

Cristian Mietlicki

Cristian Mietlicki

22/05/2009

Consigo alguma resposta para hoje ainda hehe , até mais.
GOSTEI 0
Henrique Weissmann

Henrique Weissmann

22/05/2009

Diversos fatores podem levar a este problema:

1. Algum arquivo .jar pode estar em conflito dentro de sua aplicação (provavelmente a causa mais comum). Neste caso, verifique os arquivos xalan.jar e xerces.jar. Já tive problemas com conflitos de suas versões.
 
2. O arquivo XML de configuração pode estar digitado incorretamente. Neste caso, é fácil de resolver. Basta executar o comando de verificação de arquivos XML do Eclipse ou Netbeans que ele irá apontar o erro para você.

Se possível, envie nos o log de inicialização de sua aplicação para que eu possa fazer uma análise do mesmo.
GOSTEI 0
Cristian Mietlicki

Cristian Mietlicki

22/05/2009

Isso eu consegui resolver era o web.xml , mas estou com outra dificuldade que é com o hibernate, eu fiz as configurações no meu projeto  mas não sei se está correto, quando eu executo a aplicação não acontece nada eu deixei habilitado essa tag, <property name="hibernate.hbm2ddl.auto">create</property> que é para gerar o banco de dados, e nada acontece. Nem o log está funcionando . :(
GOSTEI 0
Cristian Mietlicki

Cristian Mietlicki

22/05/2009

Quero criar minhas tabelas  direto pelo Hibernate.


Minha Classe  Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.format_sql">true</property>
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost/Shift</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>       
        <mapping class="br.com.persistencia.Teste" />
    </session-factory>
</hibernate-configuration>

Meu HibernateUtil

package br.com.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

import br.com.persistencia.BeanAbstrato;

/**
 * Classe utilitaria do Hibernate
 * @author Cristian
 * @version 1.0
 */
public class HibernateUtil {
   
    /**
     *
     */
    private static SessionFactory SESSION_FACTORY = new AnnotationConfiguration().configure().buildSessionFactory();
   
    /**
     *
     */
    private static final ThreadLocal<Session> THREAD_SESSION = new ThreadLocal<Session>();
   
    /**
     *
     */
    private static final ThreadLocal<Transaction> THREAD_TRANSACTION = new ThreadLocal<Transaction>();
   
    /**
     *
     * @return
     */
    protected SessionFactory getSESSION_FACTORY() {
        return SESSION_FACTORY;
    }
   
    /**
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    protected static Session getSession() throws Exception {
        Session s = (Session)  THREAD_SESSION.get();
        try {
            if (s == null || !s.isOpen()) {
                s = SESSION_FACTORY.openSession();
                THREAD_SESSION.set(s);
            }
        } catch (HibernateException ex) {
            throw new Exception(ex);
        }
       
        return s;
    }
   
    /**
     *
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    protected static void closeSession() throws Exception {
        try {
             Session s = (Session) THREAD_SESSION.get();
            //Session s = (Session) getSESSION_FACTORY();
            THREAD_SESSION.set(null);
            if (s != null && s.isOpen())
                s.close();
        } catch (HibernateException ex) {
            throw new Exception(ex);
        }
    }
   
    /**
     *
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    protected static void beginTransaction() throws Exception {
        Transaction tx = (Transaction)  THREAD_TRANSACTION.get();
        try {
            if (tx == null) {
                tx =  getSession().beginTransaction();
                 THREAD_TRANSACTION.set(tx);
            }
        } catch (HibernateException ex) {
             closeSession();
            throw new Exception(ex);
        }
    }
   
    /**
     *
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    protected static void commitTransaction() throws Exception {
        Transaction tx = (Transaction) THREAD_TRANSACTION.get();
        try {
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
                tx.commit();
            THREAD_TRANSACTION.set(null);
        } catch (HibernateException ex) {
             rollbackTransaction();
            throw new Exception(ex);
        }
    }
   
    /**
     *
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    protected static void rollbackTransaction() throws Exception {
        Transaction tx = (Transaction) THREAD_TRANSACTION.get();
        try {
             THREAD_TRANSACTION.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
                tx.rollback();
        } catch (HibernateException ex) {
            throw new Exception(ex);
        }
    }
   
    /**
     *
     * @param bean
     * @throws Exception
     */
    public static void save(BeanAbstrato bean) throws Exception {
        try {
            beginTransaction();
            getSession().save(bean);
            getSession().flush();
            commitTransaction();
        } catch (HibernateException e) {
            rollbackTransaction();           
            //throw new Exception("Falha ao salvar o objeto: " + bean.toString() + "(" + e.getMessage() + ")",e.getCause());
            e.printStackTrace();
        }
    }
   
    /**
     *
     * @param bean
     * @throws Exception
     */
    public static void delete(BeanAbstrato bean) throws Exception {
        try {
            beginTransaction();   
            getSession().clear();
            getSession().delete(bean);
            getSession().flush();
            commitTransaction();
        } catch (HibernateException e) {
            rollbackTransaction();
            throw new Exception("Falha ao deletar o objeto: " + bean.toString() + "(" + e.getMessage() + ")",e.getCause());
        }
    }
   
    /**
     *
     * @param bean
     * @throws Exception
     */
    public static void update(BeanAbstrato bean) throws Exception {
        try {
            beginTransaction();
            getSession().clear();
            getSession().update(bean);
            getSession().flush();
            commitTransaction();
        } catch (HibernateException e) {
            rollbackTransaction();
            throw new Exception("Falha ao atualizar o objeto: " + bean.toString() + "(" + e.getMessage() + ")",e.getCause());
        }
    }
   
    /**
     *
     * @param bean
     * @throws Exception
     */
    public static void saveOrUpdate(BeanAbstrato bean) throws Exception {
        try {
            beginTransaction();
            getSession().clear();
            getSession().saveOrUpdate(bean);
            getSession().flush();
            commitTransaction();
        } catch (HibernateException e) {
            rollbackTransaction();
            throw new Exception("Falha ao atualizar o objeto: " + bean.toString() + "(" + e.getMessage() + ")",e.getCause());
        }
    }
   
    /**
     *
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List find(String query) throws Exception {
        try {           
            beginTransaction();
            getSession().clear();
            Query executeQuery = getSession().createQuery(query);
            List ListaObjetos = executeQuery.list();
            return ListaObjetos;
           
        } catch(Exception e) {
            if((e.getCause() != null) && (e.getCause().getMessage()!=null)) {
                rollbackTransaction();
                throw new Exception(e.getCause().getMessage());
            }
            rollbackTransaction();
           
            throw new Exception(e);
        }       
    }
   
    /**
     * Metodo responsavel por trazer um objeto da classe passada como parametro
     * @param refClass
     * @param key
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Object load(Class refClass,Serializable key) throws Exception {
       
        getSession().clear();
        return getSession().get(refClass, key);
    }
   
    /**
     *
     * @param query
     * @param session
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List createNativeQueryList(String query, Session session) throws Exception {
        List list = null;
        try {
            beginTransaction();
            list = session.createSQLQuery(query).list();
            commitTransaction();
            return list;
        } catch (Exception e) {
            if ((e.getCause() != null) && (e.getCause().getMessage() != null))
               throw new Exception(e.getCause().getMessage());
            throw new Exception(e);
        }
    }
   
    /**
     *
     * @param query
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List createNativeQueryList(String query) throws Exception {
        try {
            return createNativeQueryList(query, getSession());
        } catch (Exception e) {
            if ((e.getCause() != null) && (e.getCause().getMessage() != null))
               throw new Exception(e.getCause().getMessage());
            throw new Exception(e);
        }
    }   
   
    @SuppressWarnings("unchecked")
    public static List find(BeanAbstrato bean) throws Exception {
        try {
            beginTransaction();
            List listAll = getSession().createCriteria(bean.getClass()).list();
            commitTransaction();
           
            return listAll;
        } catch(Exception e) {
            if((e.getCause() != null) && (e.getCause().getMessage()!=null)) {
                rollbackTransaction();
                throw new Exception(e.getCause().getMessage());
            }
            rollbackTransaction();           
            throw new Exception(e);
        }
       
    }
}

GOSTEI 0
Henrique Weissmann

Henrique Weissmann

22/05/2009

Cristian,

verifique os seguintes pontos em sua aplicação:

1. No banco de dados que você está tentando acessar, você possui acesso a criação de tabelas, etc?
2. O banco de dados que você irá popular existe? O Hibernate não cria os bancos de dados, mas sim as tabelas presentes no mesmo.
3. A sua classe Teste estão com todas as anotações necessárias usadas pelo Hibernate?

Sugestão: na propriedade hibernate.hbm2ddl.auto utilize o valor update ao invés de create. Isto porque o update irá garantirq ue suas tabelas não sejam destruídas na próxima execução de sua aplicação.

4. A aplicação gera algum stacktrace ao ser executada? Em caso afirmativo (99% de chance), envie-me o stacktrace para que eu possa analizá-lo, ok?
GOSTEI 0
Cristian Mietlicki

Cristian Mietlicki

22/05/2009

org/slf4j/LoggerFactory tá dando esse erro , sabe o que pode ser?
GOSTEI 0
Henrique Weissmann

Henrique Weissmann

22/05/2009

Não conheço esta classe.
GOSTEI 0
Devmedia

Devmedia

22/05/2009

Conforme pedido do cliente, estamos trocando o chamado de consultor.
GOSTEI 0
Dyego Carmo

Dyego Carmo

22/05/2009

Opa , estarei verificando e demanha cedo eu retorno !

Obrigado !
GOSTEI 0
Dyego Carmo

Dyego Carmo

22/05/2009

Adicione em seu CLASSPATH da aplicacao a biblioteca :

slf4j-log4j12.jar

Ela vem no pacote Hibernate EntityManager ...


Teste e depois me avise...

GOSTEI 0
Cristian Mietlicki

Cristian Mietlicki

22/05/2009

Eu ja resolvi esse problema , mesmo assim obrigado.
GOSTEI 0
Dyego Carmo

Dyego Carmo

22/05/2009

Posso marcar como concluido ?
GOSTEI 0
Cristian Mietlicki

Cristian Mietlicki

22/05/2009

Pode sim.
GOSTEI 0
POSTAR