How do I get user id in a session?

0

I'm doing a project using jsp and servlet, I need when a user logs in, his id is stored in the session, so that with this id, the system knows that this id user is making changes to their (Example, phone change). How could I do that?

Control:

public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, SQLException, ServletException{
    String login = request.getParameter("usuario");
    String senha = request.getParameter("senha");

    Usuario usuario = new Usuario();
    usuario.setEmail(login);
    usuario.setSenha(senha);

    UsuarioDAO usuarioDAO = new UsuarioDAO();
    Usuario usuarioAutenticado = usuarioDAO.validar(usuario);

    if (usuarioAutenticado !=null){
        HttpSession sessaoUsuario = request.getSession();
        sessaoUsuario.setAttribute("usuario",usuarioAutenticado);
        sessaoUsuario.setMaxInactiveInterval(10);
        response.sendRedirect("home.html");
    }else{
        response.sendRedirect("erroLogin.html");
    }
}

DAO:

public Usuario validar(Usuario usuario) throws ClassNotFoundException, SQLException{

    Connection con = FabricaConexao.getConexao();

    Usuario us= null;

    PreparedStatement comando = con.prepareStatement("select * from usuario where email = ? and senha=?");
    comando.setString(1,usuario.getEmail());
    comando.setString(2,usuario.getSenha());

    ResultSet resultado = comando.executeQuery();

    if (resultado.next()){
        us=new Usuario();
        us.setEmail(resultado.getString("email"));
        us.setSenha(resultado.getString("senha"));
        //us.setPerfilAcesso(resultado.getString("perfil_acesso"));

    }

    con.close();
    return us;
}

HTML:

<form role="form" action="login" method="POST" >
            <label for="usuario">Usuario (e-mail): </label><br>
            <input type="text" name="usuario" id=usuario required><br>
            <label for="senha">Senha </label><br>
            <input type="password" name="senha" id=senha required><br>

            <br><input type="submit" class="btn btn-login" value="Login">
            <br><a href=cadastroConta.html>Nao possui conta? Click aqui</a>
        </form>
    
asked by anonymous 02.12.2016 / 00:26

1 answer

1

Celina, you already have the saved user ID in the session.

Well, when you put:

sessaoUsuario.setAttribute("usuario",usuarioAutenticado);

From there, you can retrieve the user ID at any time, either in the Servlets or in the JSPs. You can do this:

Servlets

Usuario usuario = (Usuario)request.getAttribute("usuario");
Long id = usuario.getId(); //Aqui você ja tem o id do usuário

JSP (Using JSTL)

${sessionScope.usuario.id}

For security reasons, you can just put the ID, as @RosSantos suggested:

request.getSession().setAttribute("idUsuario", usuarioAutenticado.getId());

Since it is common for the user object to contain a senha attribute, for example.

I hope I have helped.

    
02.12.2016 / 22:40