3

Estou desenvolvendo uma aplicação para aprender, e ao tentar acessar a aplicação (JSF) o Hibernate não retorna dados. Tem alguma ideia?

Segue minha classe Filter:

package br.com.importacao.filters;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;



/***
 * ESSE FILTER VAI SER CHAMADO TODA VEZ QUE FOR REALIZADO 
 * UMA REQUISIÇÃO PARA O FACES SERVLET.
 * */


@WebFilter(servletNames = {"Faces Servlet"})
public class JPAFilter implements Filter{

    private EntityManagerFactory entityManagerFactory;

    private String persistence_unit_name = "unit_app";

    public  JPAFilter() {

    }

    public void destroy() {
        this.entityManagerFactory.close();
    } 

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {


        //CRIANDO UM ENTITYMANAGER
        EntityManager entityManager = this.entityManagerFactory.createEntityManager();

        //ADICIONANDO ELE NA REQUISIÇÃO
        req.setAttribute("entityManager", entityManager);

        //INICIANDO UMA TRANSAÇÃO
        entityManager.getTransaction().begin();

        //INICIANDO FACES SERVLET
        chain.doFilter(req, resp);

        try {
            //SE NÃO TIVER ERRO NA OPERAÇÃO ELE EXECUTA O COMMIT
            entityManager.getTransaction().commit();

        } catch (Exception e) {
            //SE TIVER ERRO NA OPERAÇÃO É EXECUTADO O rollback
            entityManager.getTransaction().rollback();
        } finally {

            entityManager.close();

        }
    }

    public void init(FilterConfig fConfig) throws ServletException {

        //CRIA O entityManagerFactory COM OS PARÂMETROS DEFINIDOS NO persistence.xml
        this.entityManagerFactory = Persistence.createEntityManagerFactory(this.persistence_unit_name);

    }

}

Classe Autenticação:

package br.com.importacao.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.importacao.model.UsuarioModel;

@WebFilter("/sistema/*")
public class AutenticacaoFilter implements Filter {

    @Override
    public void destroy() {     
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpSession         httpSession         = ((HttpServletRequest) request).getSession();
        HttpServletRequest  httpServletRequest  =(HttpServletRequest)  request;
        HttpServletResponse httpServletResponse =(HttpServletResponse) response;

        if(httpServletRequest.getRequestURI().indexOf("index.xhtml") <= -1) {

            UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("Usuário Autenticado");
            if (usuarioModel == null) {
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+ "/index.xhtml");
            } 
            else {
                    chain.doFilter(request, response);
            }
        }
        else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig fConfig) throws ServletException {        
    }

}

Arquivo de persistência:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="unit_app" transaction-type="RESOURCE_LOCAL">
        <description>
            ARQUIVO DE PERSISTÊNCIA JPA E HIBERNATE            
        </description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>        
            <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://127.0.0.1\SQL2014:1433;dataBaseName=Aplicacao" />
            <property name="javax.persistence.jdbc.user" value="sa" />
            <property name="javax.persistence.jdbc.password" value="sql2014" />


            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

E o log após tentar logar na aplicação:

INFO: HHH000204: Processing PersistenceUnitInfo [ name: unit_app ...] set 10, 2018 11:58:14 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.0.Final} set 10, 2018 11:58:14 PM org.hibernate.cfg.Environment INFO: HHH000206: hibernate.properties not found set 10, 2018 11:58:14 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist set 10, 2018 11:58:16 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final} set 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!) set 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://127.0.0.1\SQL2014:1433;dataBaseName=Aplicacao] set 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000046: Connection properties: {user=sa, password=****} set 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000006: Autocommit mode: false set 10, 2018 11:58:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 20 (min=1) set 10, 2018 11:58:27 PM org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect set 10, 2018 11:58:30 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory INFO: HHH000397: Using ASTQueryTranslatorFactory set 10, 2018 11:58:36 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000228: Running hbm2ddl schema update set 10, 2018 11:58:36 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000102: Fetching database metadata set 10, 2018 11:58:37 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000396: Updating schema set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000261: Table found: Aplicacao.dbo.tbPessoa set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000037: Columns: [id_usuario_cadastro, id_pessoa, id_usuario, fl_sexo, nm_pessoa, dt_cadastro, ds_email, fl_origemcadastro, ds_endereco] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000108: Foreign keys: [fk_tbusuario_idusuario, fk_6f0fndvdml1p57xaedm3x9hn] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000126: Indexes: [pk_tbpessoa_idpessoa] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000261: Table found: Aplicacao.dbo.tbUsuario set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000037: Columns: [id_usuario, ds_senha, ds_login] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000108: Foreign keys: [] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000126: Indexes: [pk_tbusuario_idusuario] set 10, 2018 11:58:45 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete set 10, 2018 11:58:47 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deploying web application directory C:\Servers\apache-tomcat-8.0.53\webapps\docs set 10, 2018 11:58:52 PM org.apache.jasper.servlet.TldScanner scanJars INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. set 10, 2018 11:58:52 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deployment of web application directory C:\Servers\apache-tomcat-8.0.53\webapps\docs has finished in 5,451 ms set 10, 2018 11:58:52 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deploying web application directory C:\Servers\apache-tomcat-8.0.53\webapps\examples set 10, 2018 11:59:05 PM org.apache.jasper.servlet.TldScanner scanJars INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. set 10, 2018 11:59:05 PM org.apache.catalina.core.ApplicationContext log INFORMAÇÕES: ContextListener: contextInitialized() set 10, 2018 11:59:05 PM org.apache.catalina.core.ApplicationContext log INFORMAÇÕES: SessionListener: contextInitialized() set 10, 2018 11:59:05 PM org.apache.catalina.core.ApplicationContext log INFORMAÇÕES: ContextListener: attributeAdded('StockTicker', 'async.Stockticker@1d0af75') set 10, 2018 11:59:05 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deployment of web application directory C:\Servers\apache-tomcat-8.0.53\webapps\examples has finished in 12,551 ms set 10, 2018 11:59:05 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deploying web application directory C:\Servers\apache-tomcat-8.0.53\webapps\host-manager set 10, 2018 11:59:10 PM org.apache.jasper.servlet.TldScanner scanJars INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. set 10, 2018 11:59:10 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deployment of web application directory C:\Servers\apache-tomcat-8.0.53\webapps\host-manager has finished in 4,901 ms set 10, 2018 11:59:10 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deploying web application directory C:\Servers\apache-tomcat-8.0.53\webapps\manager set 10, 2018 11:59:18 PM org.apache.jasper.servlet.TldScanner scanJars INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. set 10, 2018 11:59:18 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deployment of web application directory C:\Servers\apache-tomcat-8.0.53\webapps\manager has finished in 8,092 ms set 10, 2018 11:59:18 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deploying web application directory C:\Servers\apache-tomcat-8.0.53\webapps\ROOT set 10, 2018 11:59:24 PM org.apache.jasper.servlet.TldScanner scanJars INFORMAÇÕES: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. set 10, 2018 11:59:24 PM org.apache.catalina.startup.HostConfig deployDirectory INFORMAÇÕES: Deployment of web application directory C:\Servers\apache-tomcat-8.0.53\webapps\ROOT has finished in 5,672 ms set 10, 2018 11:59:24 PM org.apache.coyote.AbstractProtocol start INFORMAÇÕES: Starting ProtocolHandler ["http-nio-8080"] set 10, 2018 11:59:24 PM org.apache.coyote.AbstractProtocol start INFORMAÇÕES: Starting ProtocolHandler ["ajp-nio-8009"] set 10, 2018 11:59:24 PM org.apache.catalina.startup.Catalina start INFORMAÇÕES: Server startup in 119273 ms

Hibernate:

    select
        usuarioent0_.id_usuario as id_usuar1_1_,
        usuarioent0_.ds_senha as ds_senha2_1_,
        usuarioent0_.ds_login as ds_login3_1_ 
    from
        tbUsuario usuarioent0_ 
    where
        usuarioent0_.ds_login=? 
        and usuarioent0_.ds_senha=?
4
  • Coloca sua página JSF também
    – Edjane
    12/09/2018 às 22:54
  • Consegui resolver. Mas obrigado.
    – Parreira
    8/10/2018 às 17:12
  • @Pereira compartilhe a solução conosco :). Você pode responder sua própria pergunta
    – Dherik
    24/10/2018 às 13:16
  • O problema estava na definição: UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("Usuário Autenticado"); o correto era UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("usuarioAutenticado");
    – Parreira
    22/11/2018 às 11:16

1 Resposta 1

1

Consegui resolver o problema, estava na definição:

UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("Usuário Autenticado");                                                                     

O correto era:

UsuarioModel usuarioModel = (UsuarioModel) httpSession.getAttribute("usuarioAutenticado");

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .