Today, I make my connection to the database using jpa
. In my persistence
I have 2 PU, one is to connect to my "Manager", which is where my database addresses are, and the other is to connect to the clients database.
Until then I did, my problem is the following, when I make a connection with an X client, it enters everything right, but then the client Y decides to enter the system, when I make the connection, the client goes out and you can see the data of client Y.
Someone can give me a light, how do I make the client X stay logged in with their data even if the client and enter the system
Follow my persistence:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="GestorPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Entity.Cadgru</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="org.firebirdsql.jdbc.FBDriver"/>
<property name="hibernate.connection.url" value="jdbc:firebirdsql:localhost/3050:C:\BANCOS\GESTOR.FDB"/>
<property name="hibernate.connection.username" value="SYSDBA"/>
<property name="hibernate.connection.password" value="masterkey"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.FirebirdDialect"/>
</properties>
</persistence-unit>
<persistence-unit name="MitryusPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Entity.Cadusr</class>
<class>Entity.Cadloj</class>
<class>Entity.Cadfun</class>
<class>Entity.Tipcli</class>
<class>Entity.Tipven</class>
<class>Entity.Vendas</class>
<class>Entity.Venda_Sintetico</class>
<class>Entity.CodigoPin</class>
<class>Entity.Codloc</class>
<class>Entity.VendaEvolucao</class>
<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>
</persistence-unit>
</persistence>
Follow my connection:
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 ;
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();
}
}
Follow my 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.Cadusr;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
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;
public static Cadusr usu = new Cadusr();
public Cadusr buscaPorId(String gr, String usr, String senha) {
EntityManager em = Conexao.getEntityManager("0", null);
EntityTransaction tx = em.getTransaction();
tx.begin();
Cadgru cadgru = em.find(Cadgru.class, gr);
tx.commit();
em.close();
if (cadgru != null) {
EntityManager em2 = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb());
EntityTransaction tx2 = em2.getTransaction();
tx2.begin();
String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr";
Query query = em2.createQuery(jpql, Cadusr.class);
query.setParameter("nomusr", usr);
query.setParameter("pasusr", senha);
try {
retorno = (Cadusr) query.getSingleResult();
tx2.commit();
em2.close();
if (retorno == null) {
em = Conexao.getEntityManager("0", cadgru.getEndfdb());
tx = em.getTransaction();
tx.begin();
tx.commit();
em.close();
}
} 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;
}
}
}
this is my filter:
package Util;
import Entity.Cadusr;
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
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;
/**
*
* @author Felipee
*/
@WebFilter(servletNames = {"Faces Servlet"})
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
String uri = req.getRequestURI();
if (session.getAttribute("usuarioLogado") != null ||
uri.equals("/") ||
uri.equals("/index.xhtml") ||
uri.contains("javax")) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect("/MitryusReports/index.xhtml");
}
}
@Override
public void destroy() {
}
}
This is my SessionContext:
package Util;
import Entity.Cadusr;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author Felipee
*/
public class SessionContext {
private static SessionContext instance;
public static SessionContext getInstance() {
if (instance == null) {
instance = new SessionContext();
}
return instance;
}
private SessionContext() {
}
private ExternalContext currentExternalContext() {
if (FacesContext.getCurrentInstance() == null) {
throw new RuntimeException("O FacesContext não pode ser chamado fora de uma requisição HTTP");
} else {
return FacesContext.getCurrentInstance().getExternalContext();
}
}
public Cadusr getUsuarioLogado() {
return (Cadusr) getAttribute("usuarioLogado");
}
public void setUsuarioLogado(Cadusr usuario) {
setAttribute("usuarioLogado", usuario);
}
public void encerrarSessao() {
currentExternalContext().invalidateSession();
}
public Object getAttribute(String nome) {
return currentExternalContext().getSessionMap().get(nome);
}
public void setAttribute(String nome, Object valor) {
currentExternalContext().getSessionMap().put(nome, valor);
}
}
pg:
<h:head>
<meta charset="utf-8"/>
<meta name="description" content=""/>
<meta name="author" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>Vetor Sistemas - Login</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="css/your_style.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="css/smartadmin-production.min.css"/>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,300,400,700"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
</h:head>
<body >
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4" id="div_login" >
<div class="well no-padding">
<h:form id="login-form" class="smart-form client-form">
<header>
MitryusWeb
</header>
<fieldset>
<section>
<label class="label">Grupo</label>
<label class="input"> <i class="icon-append fa fa-group"></i>
<input type="text" id="gr" name="grupo" jsf:value="#{mbeanUsuario.grupo}"/>
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i> Entre com o nome do grupo</b></label>
</section>
<section>
<label class="label">Usuario</label>
<label class="input"> <i class="icon-append fa fa-user"></i>
<input type="text" name="usuario" jsf:value="#{mbeanUsuario.usuario}"/>
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i> Entre com o nome de usuario</b></label>
</section>
<section>
<label class="label">Senha</label>
<label class="input"> <i class="icon-append fa fa-lock"></i>
<input type="password" name="password" jsf:value="#{mbeanUsuario.senha}" />
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i> Entre com sua senha</b> </label>
<div class="note">
<a href="forgotpassword.html">Esqueceu a Senha?</a>
</div>
</section>
<section>
<label class="checkbox">
<input type="checkbox" name="remember" checked=""/>
<i></i>Salvar Credenciais</label>
</section>
<footer>
<h:commandButton type="submit" class="btn btn-primary" value="Entrar" action="#{mbeanUsuario.Vusuario}"/>
</footer>
</fieldset>
</h:form>
</div>
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/masked-input/jquery.maskedinput.min.js"></script>
<script src="js/app.min.js"></script>
<script>
jQuery(function($){
$("#gr").mask("****-****");
});
</script>
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.Cadusr; import Util.SessionContext; import org.apache.log4j.Logger; import javax.faces.bean.ManagedBean;
@ManagedBean
public class mbeanUsuario {
private static Logger logger = Logger.getLogger(mbeanUsuario.class);
private String Usuario;
private String Grupo;
private String senha;
public GestorDAO gestor = new GestorDAO();
public String Vusuario() {
String retorno;
Cadusr user = gestor.buscaPorId(getGrupo(), getUsuario(), getSenha());
if (user != null) {
logger.info("Tentando logar com usuário " + Usuario);
SessionContext.getInstance().setAttribute("usuarioLogado", user);
retorno = "codigo_pin.xhtml";
} else {
retorno = null;
}
return retorno;
}
/**
* @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 gr
*/
}
insira o código aqui