0
I’m having a problem, with my Session,hj I make 2 connections , one in my manager database to grab the client’s ip and database location, and another in the client’s database with the ip and database location, until then quiet , the problem is that I will have several users of various databases logged in at the same time, I am trying to implement Session by filter, so q every time I enter a different account to my previous account and replaced by the last q I entered .....
follows 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.Serializable;
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 implements Serializable{
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();
tx.commit();
Cadgru cadgru = em.find(Cadgru.class, gr);
if (cadgru != null) {
em = Conexao.getEntityManager("MitryusPU", cadgru.getEndfdb());
tx = em.getTransaction();
tx.begin();
String jpql = "select a from Cadusr a where a.nomusr = :nomusr and a.pasusr = :pasusr";
Query query = em.createQuery(jpql, Cadusr.class);
query.setParameter("nomusr", usr);
query.setParameter("pasusr", senha);
try {
retorno =(Cadusr) query.getSingleResult() ;
if (retorno == null) {
em = Conexao.getEntityManager("0", cadgru.getEndfdb());
tx = em.getTransaction();
tx.begin();
}
} catch (NoResultException nre) {
}
} else {
retorno = null;
}
tx.commit();
em.close();
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;
}
}
}
follow my 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 = "index.xhtml";
} else {
retorno = null;
}
return retorno;
}
public String doLogout() {
logger.info("Fazendo logout com usuário "
+ SessionContext.getInstance().getUsuarioLogado());
SessionContext.getInstance().encerrarSessao();
return "/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 gr
*/
}
Follow my web.inf :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<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>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>Util.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/restricted/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>faces/login.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Follow my Sessioncontext :
/*
* 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 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);
}
}
follows my Loginfilter :
/*
* 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 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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Felipee
*/
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 {
Cadusr user = null;
HttpSession sess = ((HttpServletRequest) request).getSession(false);
if (sess != null) {
user = (Cadusr) sess.getAttribute("usuarioLogado");
}
if (user == null) {
String contextPath = ((HttpServletRequest) request).getContextPath();
((HttpServletResponse) response).sendRedirect(contextPath + "/login.jsf");
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
Try removing Static from your Cadusr Usu object and see if it works.
– Armando K.
because then , it seems that it is not entering in my Loginfilter, and it is declared in my web.inf, if I put on top of my Loginfilter @Webfilter(servletNames = {"Faces Servlet"}), and do the debug it passes, so that I lose the css
– Felipe Souza
Ah, it’s happened to me a few times. I used the solution of this link here and solved my problem: http://stackoverflow.com/questions/14526574/jsf-page-style-missing-when-using-login-filter
– Armando K.