Using CDI in the app

Asked

Viewed 95 times

1

People have a problem , on my login screen I can inject the in a good, when I step to the second screen that would be the Dash , I can not inject , he only brings me with null ....

Segue Conexao :

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CDI;

import CDI.Corporativo;
import Entity.Cadgru;
import java.io.Serializable;
import java.util.Properties;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;

/**
 *
 * @author Felipe
 */
@Named
@ApplicationScoped
public class ConexaoCDI implements Serializable {

    public static Cadgru grupo = new Cadgru();
    private static EntityManagerFactory mitryusFactory;

    @PersistenceUnit(unitName = "GestorPU")
    private  EntityManagerFactory gestorFactory;

    @Produces
    @RequestScoped
    @Gestor
    public EntityManager getGestorEntityManager() {
        return gestorFactory.createEntityManager();
    }

    /**
     *
     * @return
     */
    @Produces
    @RequestScoped
    @Mitryus
    public EntityManager getMitryusEntityManager() {
        return getMitryusFactory().createEntityManager();
    }

    /**
     *
     * @param em
     */
    public void close(@Disposes @Any EntityManager em) {
        em.close();
    }

    public void adicionaCadgru(Cadgru cadgru) {
        this.grupo = cadgru;
    }

    private EntityManagerFactory getMitryusFactory() {
        if (mitryusFactory == null) {
            Properties props = new Properties();

            props.setProperty("javax.persistence.jdbc.url", "jdbc:firebirdsql:" + grupo.getEndsrv() + "/3050:" + grupo.getEndfdb());
            mitryusFactory = Persistence.createEntityManagerFactory("MitryusPU", props);
        }
        return mitryusFactory;
    }
}

Follows the DAO

   private EntityManager emMitryus;

@Inject
public DAOUtil(@Mitryus EntityManager manager) {
    this.emMitryus = manager;
}
public UsuarioSessao usuario;

public DAOUtil() {
    usuario = (UsuarioSessao) getSession().getAttribute("usuario");
}

public Cadusr verificaUsuario(String usuario, String senha) {
    Cadusr retorno = new Cadusr();
    String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr and a.usratv = 'S'";
    Query query = emMitryus.createQuery(jpql, Cadusr.class);
    query.setParameter("nomusr", usuario);
    query.setParameter("pasusr", senha);
    try {
        retorno = (Cadusr) query.getSingleResult();
    } catch (NoResultException nre) {

    }
    return retorno;
}

public String buscaLojaId(String str) {
    String hql = "select a.nomloj from Cadloj a where a.codloj = :str";
    Query query = emMitryus.createQuery(hql);
    query.setParameter("str", Integer.valueOf(str));
    String loja = new String();
    try {
        loja = (String) query.getSingleResult();
    } catch (Exception e) {
    }
    return loja;
}

Follow the login bean(Where to inject right)

@ManagedBean(name = "login")

@Requestscoped public class mbean_001_Login {

private String grupo;
private String usuario;
private String senha;
@Inject
private DAO_Gestor daoGestor;
@Inject
private DAOUtil daoMitryus;

public String login() {
    if (grupo.equals("") || usuario.equals("") || senha.equals("")) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Informações", "Favor indicar grupo , usuario e senha"));

        return "/seguranca/login.jsf?faces-redirect=true";

    } else {
        System.out.println("Usuario   : " + getUsuario());
        System.out.println("Senha     : " + getSenha());
        String retorno = "";
        if (daoGestor.verificaGrupo(grupo) != null) {
            Cadusr usr = daoMitryus.verificaUsuario(usuario, senha);

            if (usr != null) {
                /*SE INSERIR ALGO NO USUARIO SESSÃO NÃO ESQUECER DE AJUSTAR NO DAO_001_GESTOR (CHAMADA MITRYUSWEB)*/

                UsuarioSessao us = new UsuarioSessao();
                us.setGrupo(grupo);
                us.setSenha(senha);
                us.setUsuario(usuario);
                us.setCodusr(String.valueOf(usr.getCodusr()));
                us.setAdm(String.valueOf(usr.getAdmsis()));
                us.setLojtra(String.valueOf(usr.getCodloj()));
                us.setValsen(us.getValsen());
                us.setCodtrm("315");
                us.setCodloj(us.getLojtra());
                us.setNomloj(daoMitryus.buscaLojaId(us.getLojtra()));
                us.setTipsis(daoMitryus.buscaTipoSistema(Integer.valueOf(us.getCodloj())));
                us.setDataMinimaEmissaoRelatorio(daoMitryus.SetaDataMinimaMovimento(us));
                String lj = "";
                List<String> lojas_permitidas = new ArrayList<>();
                for (int i = 0; i < usr.getLojvld().length(); i++) {
                    char c = usr.getLojvld().charAt(i);
                    if (i % 2 == 0) {
                        lj = lj + c;
                    } else {
                        lj = lj + c;
                        lojas_permitidas.add(lj);
                        lj = "";
                    }
                }
                us.setLojas(lojas_permitidas);
                HttpSession sess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
                sess.setAttribute("usuario", us);
                retorno = "/app/dash.jsf?faces-redirect=true";
            } else {
                retorno = "/seguranca/login.jsf?faces-redirect=true";
            }

        }
        return retorno;
    }
}

Follow the Dash bin that does not inject :

@Managedbean(name = "Dash") @Requestscoped public final class mbean_002 {

private String numloj;
private String loja;
private  String usuario;
UsuarioSessao user;
Cadloj cadloj;
@Inject
private  DAOUtil util;

public void inicializaLoja() {
    cadloj = util.buscaCadlojId(user.getLojtra());
}


public mbean_002() {

    usuario = "teste";
    user = (UsuarioSessao) getSession().getAttribute("usuario");

    numloj = user.getLojtra();
    usuario = user.getUsuario();

    inicializaLoja();
    loja = cadloj.getNomloj();
}

}

  • @Felipesousa, and then solved that question ?

1 answer

1


You should modify the management of your bean, which is currently managed by JSF and is set out as @ManagedBean in class mbean_002 for @Named, which will be managed by CDI, This is the control inversion.

I advise checking the need to use the reserved word final, in the class declaration mbean_002, in this case you are declaring that she will not admit inheritance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.