Pessoal seguinte, hj eu tenho alguns clientes, e os dados desses clientes como servidor q o banco de dados esta e o endereco do banco esta tudo dentro de um banco de dados chamado “Gestor”, a partir do endereco desse banco de dados eu entro no banco de dados do cliente, até ai tudo bem, estou utilizando JPA fiz 2 PU para isso e to fazendo a conexao correta, o meu problema é quando eu crio os filter para sessao do usuario . Quando eu entro no mozilla com o usuario X , eu fiz so uma pg de teste para ver se estava ok, voltando quando eu entro com o cliente X E abro a pagina de teste tudo ok , quando eu entro com o cliente Y em outro navegador e atualizo a pagina do cliente X, os dados do cliente Y como ex : Loja, estao para o cliente X, mas o nome do usuario nao muda, estou colocando toda a minha codigicação :
Segue Classe de Conexão :
`package DAO;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Conexao {
private static EntityManagerFactory emf = Persistence.
createEntityManagerFactory("GestorPU");
public static EntityManager getEntityManager(String PU, String Local) {
if(PU.equals("0")){
emf = Persistence.createEntityManagerFactory("GestorPU");
}else{
Properties props = new Properties();
props.setProperty("hibernate.connection.url", "jdbc:firebirdsql:localhost/3050:" + Local);
emf = Persistence.createEntityManagerFactory(PU, props);
}
return emf.createEntityManager();
}
public static EntityManager getEntity() {
return emf.createEntityManager();
}
}
`
Segue minha Classe DAO :
`/*
- 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 DAO;
import Entity.Cadgru;
import Entity.Cadloj;
import Entity.Cadusr;
import Entity.Reljva;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Query;
/**
*
-
@author Felipee
*/
@Stateless
public class GestorDAO {Cadusr retorno;
Cadgru cadgru;
EntityManager gestorem;
EntityTransaction gestortx;
EntityManager mitryusem;
EntityTransaction mitryustx;
public static Cadusr usu = new Cadusr();public Reljva chamadaMitryus(String gr,String token) {
gestorem = Conexao.getEntityManager(“0”, null);
gestortx = gestorem.getTransaction();
gestortx.begin();cadgru = gestorem.find(Cadgru.class, gr); gestortx.commit(); gestorem.close(); mitryusem = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb()); mitryustx = mitryusem.getTransaction(); mitryustx.begin(); String jpql = "select a from Reljva a where a.TOKEN = :token"; Query query = mitryusem.createQuery(jpql, Reljva.class); query.setParameter("token", token); return (Reljva) query.getSingleResult();}
public Cadusr buscaPorId(String gr, String usr, String senha) {
gestorem = Conexao.getEntityManager(“0”, null);
gestortx = gestorem.getTransaction();
gestortx.begin();cadgru = gestorem.find(Cadgru.class, gr); gestortx.commit(); gestorem.close(); if (cadgru != null) { mitryusem = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb()); mitryustx = mitryusem.getTransaction(); mitryustx.begin(); String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr"; Query query = mitryusem.createQuery(jpql, Cadusr.class); query.setParameter("nomusr", usr); query.setParameter("pasusr", senha); try { retorno = (Cadusr) query.getSingleResult(); mitryustx.commit(); mitryusem.close(); if (retorno == null) { gestorem = Conexao.getEntityManager("0", cadgru.getEndfdb()); gestortx = gestorem.getTransaction(); gestortx.begin(); } } catch (NoResultException nre) { } } else { retorno = null; } return retorno;}
public String usuarioLogado() {
String Usuario = usu.getCodusr() + “-” + usu.getNomusr();
return Usuario;
}private String convertStringToMd5(String valor) {
MessageDigest mDigest;
try {
//Instanciamos o nosso HASH MD5, poderíamos usar outro como
//SHA, por exemplo, mas optamos por MD5.
mDigest = MessageDigest.getInstance(“MD5”);//Convert a String valor para um array de bytes em MD5 byte[] valorMD5 = mDigest.digest(valor.getBytes("UTF-8")); //Convertemos os bytes para hexadecimal, assim podemos salvar //no banco para posterior comparação se senhas StringBuffer sb = new StringBuffer(); for (byte b : valorMD5) { sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; }}
public List lojas() {
EntityManager em = Conexao.getEntity();
EntityTransaction tx = em.getTransaction();
tx.begin();
List lojas = new ArrayList<>();
String jpql = “from Cadloj”;
Query query = em.createQuery(jpql, Cadloj.class);
lojas = query.getResultList();
return lojas;}
}
`
Segue meu persistence :
`<?xml version="1.0" encoding="UTF-8"?>
org.hibernate.ejb.HibernatePersistence
Entity.Cadgru
true
org.hibernate.ejb.HibernatePersistence
Entity.Cadusr
Entity.Cadloj
Entity.Cadfun
Entity.Tipcli
Entity.Tipven
Entity.Vendas
Entity.Venda_Sintetico
Entity.CodigoPin
Entity.Codloc
Entity.VendaEvolucao
Entity.Reljva
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="org.firebirdsql.jdbc.FBDriver"/>
<property name="hibernate.connection.username" value="SYSDBA"/>
<property name="hibernate.connection.password" value="masterkey"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.FirebirdDialect"/>
</properties>
`
Segue meu LoginAuth :
`/*
- 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 filtro;
import Entity.Cadusr;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
-
@author Felipee
*/
@WebFilter(filterName = “loginAuth”, urlPatterns = {"/seguranca/login.jsf"})
public class LoginAuth implements Filter {private static final boolean debug = true;
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;public LoginAuth() {
}private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = (HttpSession) req.getSession();
Cadusr user = (Cadusr) session.getAttribute(“usuario”);
if (user == null) {
chain.doFilter(request, response);
} else {
res.sendRedirect(req.getContextPath() + “/app/index.jsf”);}}
/**
- Return the filter configuration object for this filter.
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
- Set the filter configuration object for this filter.
-
@param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
- Destroy method for this filter
*/
public void destroy() {
}
/**
- Init method for this filter
*/
public void init(FilterConfig filterConfig) {
}
/**
- Return a String representation of this object.
*/
@Override
public String toString() {
if (filterConfig == null) {
return (“NovoFilter()”);
}
StringBuffer sb = new StringBuffer(“NovoFilter(”);
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);if (stackTrace != null && !stackTrace.equals("")) { try { response.setContentType("text/html"); PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps); pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N // PENDING! Localize this for next official release pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); pw.print(stackTrace); pw.print("</pre></body>\n</html>"); //NOI18N pw.close(); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } else { try { PrintStream ps = new PrintStream(response.getOutputStream()); t.printStackTrace(ps); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } }}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}public void log(String msg) {
filterConfig.getServletContext().log(msg);
} - Return the filter configuration object for this filter.
}
`
Segue meu Bean :
`/*
- 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 Controller;
import DAO.GestorDAO;
import Entity.Cadloj;
import Entity.Cadusr;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
-
@author Felipee
*/
@ManagedBean
@SessionScoped
public class Bean implements Serializable{private String Usuario;
private String Grupo;
private String senha;
private List lojas;
private GestorDAO gestor = new GestorDAO();public String Vusuario() {
Cadusr user = getGestor().buscaPorId(getGrupo(), getUsuario(), getSenha());if ( user != null) { HttpSession sess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); sess.setAttribute("usuario", user); return "/app/index.xhtml?faces-redirect=true"; }else{ return "/seguranca/login.xhtml?faces-redirect=true"; }}
public String sair(){
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return “/seguranca/login.xhtml?faces-redirect=true”;
}/**
-
@return the Usuario
*/
public String getUsuario() {
return Usuario;
}
/**
-
@param Usuario the Usuario to set
*/
public void setUsuario(String Usuario) {
this.Usuario = Usuario;
}
/**
-
@return the Grupo
*/
public String getGrupo() {
return Grupo;
}
/**
-
@param Grupo the Grupo to set
*/
public void setGrupo(String Grupo) {
this.Grupo = Grupo;
}
/**
-
@return the senha
*/
public String getSenha() {
return senha;
}
/**
-
@param senha the senha to set
*/
public void setSenha(String senha) {
this.senha = senha;
}
/**
-
@return the lojas
*/
public List getLojas() {lojas = new GestorDAO().lojas();
return lojas;
}
/**
-
@param lojas the lojas to set
*/
public void setLojas(List lojas) {
this.lojas = lojas;
}
/**
-
@return the gestor
*/
public GestorDAO getGestor() {
return gestor;
}
/**
-
@param gestor the gestor to set
*/
public void setGestor(GestorDAO gestor) {
this.gestor = gestor;
}
-
@return the Usuario
}
`
